blob: 750b3e170fcce0229f5d75c0c10496975e3aa351 [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)) \
drh14f38b32020-08-19 23:51:54 +0000125 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\
126 && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0))
drhe4079e12019-09-27 16:33:27 +0000127# undef HAVE_GETHOSTUUID
128# define HAVE_GETHOSTUUID 1
129# else
130# warning "gethostuuid() is disabled."
131# endif
drh6bca6512015-04-13 23:05:28 +0000132# endif
133#endif
134
135
drhe89b2912015-03-03 20:42:01 +0000136#if OS_VXWORKS
137# include <sys/ioctl.h>
138# include <semaphore.h>
139# include <limits.h>
140#endif /* OS_VXWORKS */
141
142#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000143# include <sys/mount.h>
144#endif
145
drhdbe4b882011-06-20 18:00:17 +0000146#ifdef HAVE_UTIME
147# include <utime.h>
148#endif
149
drh9cbe6352005-11-29 03:13:21 +0000150/*
drh7ed97b92010-01-20 13:07:21 +0000151** Allowed values of unixFile.fsFlags
152*/
153#define SQLITE_FSFLAGS_IS_MSDOS 0x1
154
155/*
drh24efa542018-10-02 19:36:40 +0000156** If we are to be thread-safe, include the pthreads header.
drh9cbe6352005-11-29 03:13:21 +0000157*/
drhd677b3d2007-08-20 22:48:41 +0000158#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000159# include <pthread.h>
drh9cbe6352005-11-29 03:13:21 +0000160#endif
161
162/*
163** Default permissions when creating a new file
164*/
165#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
166# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
167#endif
168
danielk1977b4b47412007-08-17 15:53:36 +0000169/*
drh5adc60b2012-04-14 13:25:11 +0000170** Default permissions when creating auto proxy dir
171*/
aswiftaebf4132008-11-21 00:10:35 +0000172#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
173# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
174#endif
175
176/*
danielk1977b4b47412007-08-17 15:53:36 +0000177** Maximum supported path-length.
178*/
179#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000180
dane88ec182016-01-25 17:04:48 +0000181/*
182** Maximum supported symbolic links
183*/
184#define SQLITE_MAX_SYMLINKS 100
185
drh91eb93c2015-03-03 19:56:20 +0000186/* Always cast the getpid() return type for compatibility with
187** kernel modules in VxWorks. */
188#define osGetpid(X) (pid_t)getpid()
189
drh734c9862008-11-28 15:37:20 +0000190/*
drh734c9862008-11-28 15:37:20 +0000191** Only set the lastErrno if the error code is a real error and not
192** a normal expected return code of SQLITE_BUSY or SQLITE_OK
193*/
194#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
195
drhd91c68f2010-05-14 14:52:25 +0000196/* Forward references */
197typedef struct unixShm unixShm; /* Connection shared memory */
198typedef struct unixShmNode unixShmNode; /* Shared memory instance */
199typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
200typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000201
202/*
dane946c392009-08-22 11:39:46 +0000203** Sometimes, after a file handle is closed by SQLite, the file descriptor
204** cannot be closed immediately. In these cases, instances of the following
205** structure are used to store the file descriptor while waiting for an
206** opportunity to either close or reuse it.
207*/
dane946c392009-08-22 11:39:46 +0000208struct UnixUnusedFd {
209 int fd; /* File descriptor to close */
210 int flags; /* Flags this file descriptor was opened with */
211 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
212};
213
214/*
drh9b35ea62008-11-29 02:20:26 +0000215** The unixFile structure is subclass of sqlite3_file specific to the unix
216** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000217*/
drh054889e2005-11-30 03:20:31 +0000218typedef struct unixFile unixFile;
219struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000220 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000221 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000222 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000223 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000224 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000225 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000226 int lastErrno; /* The unix errno from last I/O error */
227 void *lockingContext; /* Locking style specific state */
drhc68886b2017-08-18 16:09:52 +0000228 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000229 const char *zPath; /* Name of the file */
230 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000231 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000232#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000233 int nFetchOut; /* Number of outstanding xFetch refs */
234 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000235 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
236 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000237 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000238#endif
drh537dddf2012-10-26 13:46:24 +0000239 int sectorSize; /* Device sector size */
240 int deviceCharacteristics; /* Precomputed device characteristics */
drh08c6d442009-02-09 17:34:07 +0000241#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000242 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000243#endif
drh7ed97b92010-01-20 13:07:21 +0000244#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000245 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000246#endif
drhf0119b22018-03-26 17:40:53 +0000247#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
248 unsigned iBusyTimeout; /* Wait this many millisec on locks */
249#endif
drh6c7d5c52008-11-21 20:32:33 +0000250#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000251 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000252#endif
drhd3d8c042012-05-29 17:02:40 +0000253#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000254 /* The next group of variables are used to track whether or not the
255 ** transaction counter in bytes 24-27 of database files are updated
256 ** whenever any part of the database changes. An assertion fault will
257 ** occur if a file is updated without also updating the transaction
258 ** counter. This test is made to avoid new problems similar to the
259 ** one described by ticket #3584.
260 */
261 unsigned char transCntrChng; /* True if the transaction counter changed */
262 unsigned char dbUpdate; /* True if any part of database file changed */
263 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000264
drh8f941bc2009-01-14 23:03:40 +0000265#endif
danf23da962013-03-23 21:00:41 +0000266
danielk1977967a4a12007-08-20 14:23:44 +0000267#ifdef SQLITE_TEST
268 /* In test mode, increase the size of this structure a bit so that
269 ** it is larger than the struct CrashFile defined in test6.c.
270 */
271 char aPadding[32];
272#endif
drh9cbe6352005-11-29 03:13:21 +0000273};
274
drhb00d8622014-01-01 15:18:36 +0000275/* This variable holds the process id (pid) from when the xRandomness()
276** method was called. If xOpen() is called from a different process id,
277** indicating that a fork() has occurred, the PRNG will be reset.
278*/
drh8cd5b252015-03-02 22:06:43 +0000279static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000280
drh0ccebe72005-06-07 22:22:50 +0000281/*
drha7e61d82011-03-12 17:02:57 +0000282** Allowed values for the unixFile.ctrlFlags bitmask:
283*/
drhf0b190d2011-07-26 16:03:07 +0000284#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
285#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
286#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000287#ifndef SQLITE_DISABLE_DIRSYNC
288# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
289#else
290# define UNIXFILE_DIRSYNC 0x00
291#endif
drhcb15f352011-12-23 01:04:17 +0000292#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000293#define UNIXFILE_DELETE 0x20 /* Delete on close */
294#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
295#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000296
297/*
drh198bf392006-01-06 21:52:49 +0000298** Include code that is common to all os_*.c files
299*/
300#include "os_common.h"
301
302/*
drh0ccebe72005-06-07 22:22:50 +0000303** Define various macros that are missing from some systems.
304*/
drhbbd42a62004-05-22 17:41:58 +0000305#ifndef O_LARGEFILE
306# define O_LARGEFILE 0
307#endif
308#ifdef SQLITE_DISABLE_LFS
309# undef O_LARGEFILE
310# define O_LARGEFILE 0
311#endif
312#ifndef O_NOFOLLOW
313# define O_NOFOLLOW 0
314#endif
315#ifndef O_BINARY
316# define O_BINARY 0
317#endif
318
319/*
drh2b4b5962005-06-15 17:47:55 +0000320** The threadid macro resolves to the thread-id or to 0. Used for
321** testing and debugging only.
322*/
drhd677b3d2007-08-20 22:48:41 +0000323#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000324#define threadid pthread_self()
325#else
326#define threadid 0
327#endif
328
drh99ab3b12011-03-02 15:09:07 +0000329/*
dane6ecd662013-04-01 17:56:59 +0000330** HAVE_MREMAP defaults to true on Linux and false everywhere else.
331*/
332#if !defined(HAVE_MREMAP)
333# if defined(__linux__) && defined(_GNU_SOURCE)
334# define HAVE_MREMAP 1
335# else
336# define HAVE_MREMAP 0
337# endif
338#endif
339
340/*
dan2ee53412014-09-06 16:49:40 +0000341** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
342** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
343*/
344#ifdef __ANDROID__
345# define lseek lseek64
346#endif
347
drhd76dba72017-07-22 16:00:34 +0000348#ifdef __linux__
349/*
350** Linux-specific IOCTL magic numbers used for controlling F2FS
351*/
danefe16972017-07-20 19:49:14 +0000352#define F2FS_IOCTL_MAGIC 0xf5
353#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
354#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
355#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
356#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
dan9d709542017-07-21 21:06:24 +0000357#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
dan9d709542017-07-21 21:06:24 +0000358#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
drhd76dba72017-07-22 16:00:34 +0000359#endif /* __linux__ */
danefe16972017-07-20 19:49:14 +0000360
361
dan2ee53412014-09-06 16:49:40 +0000362/*
drh9a3baf12011-04-25 18:01:27 +0000363** Different Unix systems declare open() in different ways. Same use
364** open(const char*,int,mode_t). Others use open(const char*,int,...).
365** The difference is important when using a pointer to the function.
366**
367** The safest way to deal with the problem is to always use this wrapper
368** which always has the same well-defined interface.
369*/
370static int posixOpen(const char *zFile, int flags, int mode){
371 return open(zFile, flags, mode);
372}
373
drh90315a22011-08-10 01:52:12 +0000374/* Forward reference */
375static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000376static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000377
drh9a3baf12011-04-25 18:01:27 +0000378/*
drh99ab3b12011-03-02 15:09:07 +0000379** Many system calls are accessed through pointer-to-functions so that
380** they may be overridden at runtime to facilitate fault injection during
381** testing and sandboxing. The following array holds the names and pointers
382** to all overrideable system calls.
383*/
384static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000385 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000386 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
387 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000388} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000389 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
390#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000391
drh58ad5802011-03-23 22:02:23 +0000392 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000393#define osClose ((int(*)(int))aSyscall[1].pCurrent)
394
drh58ad5802011-03-23 22:02:23 +0000395 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000396#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
397
drh58ad5802011-03-23 22:02:23 +0000398 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000399#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
400
drh58ad5802011-03-23 22:02:23 +0000401 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000402#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
403
404/*
405** The DJGPP compiler environment looks mostly like Unix, but it
406** lacks the fcntl() system call. So redefine fcntl() to be something
407** that always succeeds. This means that locking does not occur under
408** DJGPP. But it is DOS - what did you expect?
409*/
410#ifdef __DJGPP__
411 { "fstat", 0, 0 },
412#define osFstat(a,b,c) 0
413#else
drh58ad5802011-03-23 22:02:23 +0000414 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000415#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
416#endif
417
drh58ad5802011-03-23 22:02:23 +0000418 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000419#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
420
drh58ad5802011-03-23 22:02:23 +0000421 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000422#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000423
drh58ad5802011-03-23 22:02:23 +0000424 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000425#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
426
drhe89b2912015-03-03 20:42:01 +0000427#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000428 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000429#else
drh58ad5802011-03-23 22:02:23 +0000430 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000431#endif
432#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
433
434#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000435 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000436#else
drh58ad5802011-03-23 22:02:23 +0000437 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000438#endif
drhf9986d92016-04-18 13:09:55 +0000439#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
drhe562be52011-03-02 18:01:10 +0000440
drh58ad5802011-03-23 22:02:23 +0000441 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000442#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
443
drhe89b2912015-03-03 20:42:01 +0000444#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000445 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000446#else
drh58ad5802011-03-23 22:02:23 +0000447 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000448#endif
449#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
450 aSyscall[12].pCurrent)
451
452#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000453 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000454#else
drh58ad5802011-03-23 22:02:23 +0000455 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000456#endif
drhf9986d92016-04-18 13:09:55 +0000457#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
drhe562be52011-03-02 18:01:10 +0000458 aSyscall[13].pCurrent)
459
drh6226ca22015-11-24 15:06:28 +0000460 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000461#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000462
463#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000464 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000465#else
drh58ad5802011-03-23 22:02:23 +0000466 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000467#endif
dan0fd7d862011-03-29 10:04:23 +0000468#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000469
drh036ac7f2011-08-08 23:18:05 +0000470 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
471#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
472
drh90315a22011-08-10 01:52:12 +0000473 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
474#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
475
drh9ef6bc42011-11-04 02:24:02 +0000476 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
477#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
478
479 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
480#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
481
drhe2258a22016-01-12 00:37:55 +0000482#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000483 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000484#else
485 { "fchown", (sqlite3_syscall_ptr)0, 0 },
486#endif
dand3eaebd2012-02-13 08:50:23 +0000487#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000488
drh26f625f2018-02-19 16:34:31 +0000489#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000490 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
drh26f625f2018-02-19 16:34:31 +0000491#else
492 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
493#endif
drh6226ca22015-11-24 15:06:28 +0000494#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
495
dan4dd51442013-08-26 14:30:25 +0000496#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000497 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
498#else
499 { "mmap", (sqlite3_syscall_ptr)0, 0 },
500#endif
drh6226ca22015-11-24 15:06:28 +0000501#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000502
drhe4a08f92016-01-08 19:17:30 +0000503#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000504 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000505#else
drha8299922016-01-08 22:31:00 +0000506 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000507#endif
drh62be1fa2017-12-09 01:02:33 +0000508#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000509
drhe4a08f92016-01-08 19:17:30 +0000510#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000511 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
512#else
513 { "mremap", (sqlite3_syscall_ptr)0, 0 },
514#endif
drh6226ca22015-11-24 15:06:28 +0000515#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
516
drh24dbeae2016-01-08 22:18:00 +0000517#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000518 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000519#else
520 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
521#endif
drh6226ca22015-11-24 15:06:28 +0000522#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000523
drhe2258a22016-01-12 00:37:55 +0000524#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000525 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000526#else
527 { "readlink", (sqlite3_syscall_ptr)0, 0 },
528#endif
drh6226ca22015-11-24 15:06:28 +0000529#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000530
danaf1b36b2016-01-25 18:43:05 +0000531#if defined(HAVE_LSTAT)
532 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
533#else
534 { "lstat", (sqlite3_syscall_ptr)0, 0 },
535#endif
dancaf6b152016-01-25 18:05:49 +0000536#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000537
drhb5d013e2017-10-25 16:14:12 +0000538#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
dan16f39b62018-09-18 19:40:18 +0000539# ifdef __ANDROID__
540 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
danec9b2a12019-07-15 07:58:28 +0000541#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
dan16f39b62018-09-18 19:40:18 +0000542# else
danefe16972017-07-20 19:49:14 +0000543 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
danec9b2a12019-07-15 07:58:28 +0000544#define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
dan16f39b62018-09-18 19:40:18 +0000545# endif
drhb5d013e2017-10-25 16:14:12 +0000546#else
547 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
548#endif
danefe16972017-07-20 19:49:14 +0000549
drhe562be52011-03-02 18:01:10 +0000550}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000551
drh6226ca22015-11-24 15:06:28 +0000552
553/*
554** On some systems, calls to fchown() will trigger a message in a security
555** log if they come from non-root processes. So avoid calling fchown() if
556** we are not running as root.
557*/
558static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000559#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000560 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000561#else
562 return 0;
drh6226ca22015-11-24 15:06:28 +0000563#endif
564}
565
drh99ab3b12011-03-02 15:09:07 +0000566/*
567** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000568** "unix" VFSes. Return SQLITE_OK opon successfully updating the
569** system call pointer, or SQLITE_NOTFOUND if there is no configurable
570** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000571*/
572static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000573 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
574 const char *zName, /* Name of system call to override */
575 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000576){
drh58ad5802011-03-23 22:02:23 +0000577 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000578 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000579
580 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000581 if( zName==0 ){
582 /* If no zName is given, restore all system calls to their default
583 ** settings and return NULL
584 */
dan51438a72011-04-02 17:00:47 +0000585 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000586 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
587 if( aSyscall[i].pDefault ){
588 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000589 }
590 }
591 }else{
592 /* If zName is specified, operate on only the one system call
593 ** specified.
594 */
595 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
596 if( strcmp(zName, aSyscall[i].zName)==0 ){
597 if( aSyscall[i].pDefault==0 ){
598 aSyscall[i].pDefault = aSyscall[i].pCurrent;
599 }
drh1df30962011-03-02 19:06:42 +0000600 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000601 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
602 aSyscall[i].pCurrent = pNewFunc;
603 break;
604 }
605 }
606 }
607 return rc;
608}
609
drh1df30962011-03-02 19:06:42 +0000610/*
611** Return the value of a system call. Return NULL if zName is not a
612** recognized system call name. NULL is also returned if the system call
613** is currently undefined.
614*/
drh58ad5802011-03-23 22:02:23 +0000615static sqlite3_syscall_ptr unixGetSystemCall(
616 sqlite3_vfs *pNotUsed,
617 const char *zName
618){
619 unsigned int i;
620
621 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000622 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
623 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
624 }
625 return 0;
626}
627
628/*
629** Return the name of the first system call after zName. If zName==NULL
630** then return the name of the first system call. Return NULL if zName
631** is the last system call or if zName is not the name of a valid
632** system call.
633*/
634static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000635 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000636
637 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000638 if( zName ){
639 for(i=0; i<ArraySize(aSyscall)-1; i++){
640 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000641 }
642 }
dan0fd7d862011-03-29 10:04:23 +0000643 for(i++; i<ArraySize(aSyscall); i++){
644 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000645 }
646 return 0;
647}
648
drhad4f1e52011-03-04 15:43:57 +0000649/*
drh77a3fdc2013-08-30 14:24:12 +0000650** Do not accept any file descriptor less than this value, in order to avoid
651** opening database file using file descriptors that are commonly used for
652** standard input, output, and error.
653*/
654#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
655# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
656#endif
657
658/*
drh8c815d12012-02-13 20:16:37 +0000659** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000660** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000661**
662** If the file creation mode "m" is 0 then set it to the default for
663** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
664** 0644) as modified by the system umask. If m is not 0, then
665** make the file creation mode be exactly m ignoring the umask.
666**
667** The m parameter will be non-zero only when creating -wal, -journal,
668** and -shm files. We want those files to have *exactly* the same
669** permissions as their original database, unadulterated by the umask.
670** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
671** transaction crashes and leaves behind hot journals, then any
672** process that is able to write to the database will also be able to
673** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000674*/
drh8c815d12012-02-13 20:16:37 +0000675static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000676 int fd;
drhe1186ab2013-01-04 20:45:13 +0000677 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000678 while(1){
drh5adc60b2012-04-14 13:25:11 +0000679#if defined(O_CLOEXEC)
680 fd = osOpen(z,f|O_CLOEXEC,m2);
681#else
682 fd = osOpen(z,f,m2);
683#endif
drh5128d002013-08-30 06:20:23 +0000684 if( fd<0 ){
685 if( errno==EINTR ) continue;
686 break;
687 }
drh77a3fdc2013-08-30 14:24:12 +0000688 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000689 osClose(fd);
690 sqlite3_log(SQLITE_WARNING,
691 "attempt to open \"%s\" as file descriptor %d", z, fd);
692 fd = -1;
drh0ba36212020-02-13 13:45:04 +0000693 if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
drh5128d002013-08-30 06:20:23 +0000694 }
drhe1186ab2013-01-04 20:45:13 +0000695 if( fd>=0 ){
696 if( m!=0 ){
697 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000698 if( osFstat(fd, &statbuf)==0
699 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000700 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000701 ){
drhe1186ab2013-01-04 20:45:13 +0000702 osFchmod(fd, m);
703 }
704 }
drh5adc60b2012-04-14 13:25:11 +0000705#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000706 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000707#endif
drhe1186ab2013-01-04 20:45:13 +0000708 }
drh5adc60b2012-04-14 13:25:11 +0000709 return fd;
drhad4f1e52011-03-04 15:43:57 +0000710}
danielk197713adf8a2004-06-03 16:08:41 +0000711
drh107886a2008-11-21 22:21:50 +0000712/*
dan9359c7b2009-08-21 08:29:10 +0000713** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000714** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000715** vxworksFileId objects used by this file, all of which may be
716** shared by multiple threads.
717**
718** Function unixMutexHeld() is used to assert() that the global mutex
719** is held when required. This function is only used as part of assert()
720** statements. e.g.
721**
722** unixEnterMutex()
723** assert( unixMutexHeld() );
724** unixEnterLeave()
drh095908e2018-08-13 20:46:18 +0000725**
726** To prevent deadlock, the global unixBigLock must must be acquired
727** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
728** OK to get the pLockMutex without holding unixBigLock first, but if
729** that happens, the unixBigLock mutex must not be acquired until after
730** pLockMutex is released.
731**
732** OK: enter(unixBigLock), enter(pLockInfo)
733** OK: enter(unixBigLock)
734** OK: enter(pLockInfo)
735** ERROR: enter(pLockInfo), enter(unixBigLock)
drh107886a2008-11-21 22:21:50 +0000736*/
drh56115892018-02-05 16:39:12 +0000737static sqlite3_mutex *unixBigLock = 0;
drh107886a2008-11-21 22:21:50 +0000738static void unixEnterMutex(void){
drh095908e2018-08-13 20:46:18 +0000739 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
drh56115892018-02-05 16:39:12 +0000740 sqlite3_mutex_enter(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000741}
742static void unixLeaveMutex(void){
drh095908e2018-08-13 20:46:18 +0000743 assert( sqlite3_mutex_held(unixBigLock) );
drh56115892018-02-05 16:39:12 +0000744 sqlite3_mutex_leave(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000745}
dan9359c7b2009-08-21 08:29:10 +0000746#ifdef SQLITE_DEBUG
747static int unixMutexHeld(void) {
drh56115892018-02-05 16:39:12 +0000748 return sqlite3_mutex_held(unixBigLock);
dan9359c7b2009-08-21 08:29:10 +0000749}
750#endif
drh107886a2008-11-21 22:21:50 +0000751
drh734c9862008-11-28 15:37:20 +0000752
mistachkinfb383e92015-04-16 03:24:38 +0000753#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000754/*
755** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000756** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000757** integer lock-type.
758*/
drh308c2a52010-05-14 11:30:18 +0000759static const char *azFileLock(int eFileLock){
760 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000761 case NO_LOCK: return "NONE";
762 case SHARED_LOCK: return "SHARED";
763 case RESERVED_LOCK: return "RESERVED";
764 case PENDING_LOCK: return "PENDING";
765 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000766 }
767 return "ERROR";
768}
769#endif
770
771#ifdef SQLITE_LOCK_TRACE
772/*
773** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000774**
drh734c9862008-11-28 15:37:20 +0000775** This routine is used for troubleshooting locks on multithreaded
776** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
777** command-line option on the compiler. This code is normally
778** turned off.
779*/
780static int lockTrace(int fd, int op, struct flock *p){
781 char *zOpName, *zType;
782 int s;
783 int savedErrno;
784 if( op==F_GETLK ){
785 zOpName = "GETLK";
786 }else if( op==F_SETLK ){
787 zOpName = "SETLK";
788 }else{
drh99ab3b12011-03-02 15:09:07 +0000789 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000790 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
791 return s;
792 }
793 if( p->l_type==F_RDLCK ){
794 zType = "RDLCK";
795 }else if( p->l_type==F_WRLCK ){
796 zType = "WRLCK";
797 }else if( p->l_type==F_UNLCK ){
798 zType = "UNLCK";
799 }else{
800 assert( 0 );
801 }
802 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000803 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000804 savedErrno = errno;
805 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
806 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
807 (int)p->l_pid, s);
808 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
809 struct flock l2;
810 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000811 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000812 if( l2.l_type==F_RDLCK ){
813 zType = "RDLCK";
814 }else if( l2.l_type==F_WRLCK ){
815 zType = "WRLCK";
816 }else if( l2.l_type==F_UNLCK ){
817 zType = "UNLCK";
818 }else{
819 assert( 0 );
820 }
821 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
822 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
823 }
824 errno = savedErrno;
825 return s;
826}
drh99ab3b12011-03-02 15:09:07 +0000827#undef osFcntl
828#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000829#endif /* SQLITE_LOCK_TRACE */
830
drhff812312011-02-23 13:33:46 +0000831/*
832** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000833**
drhe6d41732015-02-21 00:49:00 +0000834** All calls to ftruncate() within this file should be made through
835** this wrapper. On the Android platform, bypassing the logic below
836** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000837*/
drhff812312011-02-23 13:33:46 +0000838static int robust_ftruncate(int h, sqlite3_int64 sz){
839 int rc;
dan2ee53412014-09-06 16:49:40 +0000840#ifdef __ANDROID__
841 /* On Android, ftruncate() always uses 32-bit offsets, even if
842 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000843 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000844 ** such attempts. */
845 if( sz>(sqlite3_int64)0x7FFFFFFF ){
846 rc = SQLITE_OK;
847 }else
848#endif
drh99ab3b12011-03-02 15:09:07 +0000849 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000850 return rc;
851}
drh734c9862008-11-28 15:37:20 +0000852
853/*
854** This routine translates a standard POSIX errno code into something
855** useful to the clients of the sqlite3 functions. Specifically, it is
856** intended to translate a variety of "try again" errors into SQLITE_BUSY
857** and a variety of "please close the file descriptor NOW" errors into
858** SQLITE_IOERR
859**
860** Errors during initialization of locks, or file system support for locks,
861** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
862*/
863static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000864 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
865 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
866 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
867 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000868 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000869 case EACCES:
drh734c9862008-11-28 15:37:20 +0000870 case EAGAIN:
871 case ETIMEDOUT:
872 case EBUSY:
873 case EINTR:
874 case ENOLCK:
875 /* random NFS retry error, unless during file system support
876 * introspection, in which it actually means what it says */
877 return SQLITE_BUSY;
878
drh734c9862008-11-28 15:37:20 +0000879 case EPERM:
880 return SQLITE_PERM;
881
drh734c9862008-11-28 15:37:20 +0000882 default:
883 return sqliteIOErr;
884 }
885}
886
887
drh734c9862008-11-28 15:37:20 +0000888/******************************************************************************
889****************** Begin Unique File ID Utility Used By VxWorks ***************
890**
891** On most versions of unix, we can get a unique ID for a file by concatenating
892** the device number and the inode number. But this does not work on VxWorks.
893** On VxWorks, a unique file id must be based on the canonical filename.
894**
895** A pointer to an instance of the following structure can be used as a
896** unique file ID in VxWorks. Each instance of this structure contains
897** a copy of the canonical filename. There is also a reference count.
898** The structure is reclaimed when the number of pointers to it drops to
899** zero.
900**
901** There are never very many files open at one time and lookups are not
902** a performance-critical path, so it is sufficient to put these
903** structures on a linked list.
904*/
905struct vxworksFileId {
906 struct vxworksFileId *pNext; /* Next in a list of them all */
907 int nRef; /* Number of references to this one */
908 int nName; /* Length of the zCanonicalName[] string */
909 char *zCanonicalName; /* Canonical filename */
910};
911
912#if OS_VXWORKS
913/*
drh9b35ea62008-11-29 02:20:26 +0000914** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000915** variable:
916*/
917static struct vxworksFileId *vxworksFileList = 0;
918
919/*
920** Simplify a filename into its canonical form
921** by making the following changes:
922**
923** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000924** * convert /./ into just /
925** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000926**
927** Changes are made in-place. Return the new name length.
928**
929** The original filename is in z[0..n-1]. Return the number of
930** characters in the simplified name.
931*/
932static int vxworksSimplifyName(char *z, int n){
933 int i, j;
934 while( n>1 && z[n-1]=='/' ){ n--; }
935 for(i=j=0; i<n; i++){
936 if( z[i]=='/' ){
937 if( z[i+1]=='/' ) continue;
938 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
939 i += 1;
940 continue;
941 }
942 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
943 while( j>0 && z[j-1]!='/' ){ j--; }
944 if( j>0 ){ j--; }
945 i += 2;
946 continue;
947 }
948 }
949 z[j++] = z[i];
950 }
951 z[j] = 0;
952 return j;
953}
954
955/*
956** Find a unique file ID for the given absolute pathname. Return
957** a pointer to the vxworksFileId object. This pointer is the unique
958** file ID.
959**
960** The nRef field of the vxworksFileId object is incremented before
961** the object is returned. A new vxworksFileId object is created
962** and added to the global list if necessary.
963**
964** If a memory allocation error occurs, return NULL.
965*/
966static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
967 struct vxworksFileId *pNew; /* search key and new file ID */
968 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
969 int n; /* Length of zAbsoluteName string */
970
971 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000972 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000973 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000974 if( pNew==0 ) return 0;
975 pNew->zCanonicalName = (char*)&pNew[1];
976 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
977 n = vxworksSimplifyName(pNew->zCanonicalName, n);
978
979 /* Search for an existing entry that matching the canonical name.
980 ** If found, increment the reference count and return a pointer to
981 ** the existing file ID.
982 */
983 unixEnterMutex();
984 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
985 if( pCandidate->nName==n
986 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
987 ){
988 sqlite3_free(pNew);
989 pCandidate->nRef++;
990 unixLeaveMutex();
991 return pCandidate;
992 }
993 }
994
995 /* No match was found. We will make a new file ID */
996 pNew->nRef = 1;
997 pNew->nName = n;
998 pNew->pNext = vxworksFileList;
999 vxworksFileList = pNew;
1000 unixLeaveMutex();
1001 return pNew;
1002}
1003
1004/*
1005** Decrement the reference count on a vxworksFileId object. Free
1006** the object when the reference count reaches zero.
1007*/
1008static void vxworksReleaseFileId(struct vxworksFileId *pId){
1009 unixEnterMutex();
1010 assert( pId->nRef>0 );
1011 pId->nRef--;
1012 if( pId->nRef==0 ){
1013 struct vxworksFileId **pp;
1014 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
1015 assert( *pp==pId );
1016 *pp = pId->pNext;
1017 sqlite3_free(pId);
1018 }
1019 unixLeaveMutex();
1020}
1021#endif /* OS_VXWORKS */
1022/*************** End of Unique File ID Utility Used By VxWorks ****************
1023******************************************************************************/
1024
1025
1026/******************************************************************************
1027*************************** Posix Advisory Locking ****************************
1028**
drh9b35ea62008-11-29 02:20:26 +00001029** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +00001030** section 6.5.2.2 lines 483 through 490 specify that when a process
1031** sets or clears a lock, that operation overrides any prior locks set
1032** by the same process. It does not explicitly say so, but this implies
1033** that it overrides locks set by the same process using a different
1034** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +00001035**
1036** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +00001037** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1038**
1039** Suppose ./file1 and ./file2 are really the same file (because
1040** one is a hard or symbolic link to the other) then if you set
1041** an exclusive lock on fd1, then try to get an exclusive lock
1042** on fd2, it works. I would have expected the second lock to
1043** fail since there was already a lock on the file due to fd1.
1044** But not so. Since both locks came from the same process, the
1045** second overrides the first, even though they were on different
1046** file descriptors opened on different file names.
1047**
drh734c9862008-11-28 15:37:20 +00001048** This means that we cannot use POSIX locks to synchronize file access
1049** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001050** to synchronize access for threads in separate processes, but not
1051** threads within the same process.
1052**
1053** To work around the problem, SQLite has to manage file locks internally
1054** on its own. Whenever a new database is opened, we have to find the
1055** specific inode of the database file (the inode is determined by the
1056** st_dev and st_ino fields of the stat structure that fstat() fills in)
1057** and check for locks already existing on that inode. When locks are
1058** created or removed, we have to look at our own internal record of the
1059** locks to see if another thread has previously set a lock on that same
1060** inode.
1061**
drh9b35ea62008-11-29 02:20:26 +00001062** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1063** For VxWorks, we have to use the alternative unique ID system based on
1064** canonical filename and implemented in the previous division.)
1065**
danielk1977ad94b582007-08-20 06:44:22 +00001066** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001067** descriptor. It is now a structure that holds the integer file
1068** descriptor and a pointer to a structure that describes the internal
1069** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001070** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001071** point to the same locking structure. The locking structure keeps
1072** a reference count (so we will know when to delete it) and a "cnt"
1073** field that tells us its internal lock status. cnt==0 means the
1074** file is unlocked. cnt==-1 means the file has an exclusive lock.
1075** cnt>0 means there are cnt shared locks on the file.
1076**
1077** Any attempt to lock or unlock a file first checks the locking
1078** structure. The fcntl() system call is only invoked to set a
1079** POSIX lock if the internal lock structure transitions between
1080** a locked and an unlocked state.
1081**
drh734c9862008-11-28 15:37:20 +00001082** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001083**
1084** If you close a file descriptor that points to a file that has locks,
1085** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001086** released. To work around this problem, each unixInodeInfo object
1087** maintains a count of the number of pending locks on tha inode.
1088** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001089** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001090** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001091** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001092** be closed and that list is walked (and cleared) when the last lock
1093** clears.
1094**
drh9b35ea62008-11-29 02:20:26 +00001095** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001096**
drh9b35ea62008-11-29 02:20:26 +00001097** Many older versions of linux use the LinuxThreads library which is
1098** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001099** A cannot be modified or overridden by a different thread B.
1100** Only thread A can modify the lock. Locking behavior is correct
1101** if the appliation uses the newer Native Posix Thread Library (NPTL)
1102** on linux - with NPTL a lock created by thread A can override locks
1103** in thread B. But there is no way to know at compile-time which
1104** threading library is being used. So there is no way to know at
1105** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001106** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001107** current process.
drh5fdae772004-06-29 03:29:00 +00001108**
drh8af6c222010-05-14 12:43:01 +00001109** SQLite used to support LinuxThreads. But support for LinuxThreads
1110** was dropped beginning with version 3.7.0. SQLite will still work with
1111** LinuxThreads provided that (1) there is no more than one connection
1112** per database file in the same process and (2) database connections
1113** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001114*/
1115
1116/*
1117** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001118** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001119*/
1120struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001121 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001122#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001123 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001124#else
drh25ef7f52016-12-05 20:06:45 +00001125 /* We are told that some versions of Android contain a bug that
1126 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1127 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1128 ** To work around this, always allocate 64-bits for the inode number.
1129 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1130 ** but that should not be a big deal. */
1131 /* WAS: ino_t ino; */
1132 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001133#endif
1134};
1135
1136/*
drhbbd42a62004-05-22 17:41:58 +00001137** An instance of the following structure is allocated for each open
drh24efa542018-10-02 19:36:40 +00001138** inode.
drhbbd42a62004-05-22 17:41:58 +00001139**
danielk1977ad94b582007-08-20 06:44:22 +00001140** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001141** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001142** object keeps a count of the number of unixFile pointing to it.
drhda6dc242018-07-23 21:10:37 +00001143**
1144** Mutex rules:
1145**
drh095908e2018-08-13 20:46:18 +00001146** (1) Only the pLockMutex mutex must be held in order to read or write
drhda6dc242018-07-23 21:10:37 +00001147** any of the locking fields:
drhef52b362018-08-13 22:50:34 +00001148** nShared, nLock, eFileLock, bProcessLock, pUnused
drhda6dc242018-07-23 21:10:37 +00001149**
1150** (2) When nRef>0, then the following fields are unchanging and can
1151** be read (but not written) without holding any mutex:
1152** fileId, pLockMutex
1153**
drhef52b362018-08-13 22:50:34 +00001154** (3) With the exceptions above, all the fields may only be read
drhda6dc242018-07-23 21:10:37 +00001155** or written while holding the global unixBigLock mutex.
drh095908e2018-08-13 20:46:18 +00001156**
1157** Deadlock prevention: The global unixBigLock mutex may not
1158** be acquired while holding the pLockMutex mutex. If both unixBigLock
1159** and pLockMutex are needed, then unixBigLock must be acquired first.
drhbbd42a62004-05-22 17:41:58 +00001160*/
drh8af6c222010-05-14 12:43:01 +00001161struct unixInodeInfo {
1162 struct unixFileId fileId; /* The lookup key */
drhda6dc242018-07-23 21:10:37 +00001163 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1164 int nShared; /* Number of SHARED locks held */
1165 int nLock; /* Number of outstanding file locks */
1166 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1167 unsigned char bProcessLock; /* An exclusive process lock is held */
drhef52b362018-08-13 22:50:34 +00001168 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh734c9862008-11-28 15:37:20 +00001169 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001170 unixShmNode *pShmNode; /* Shared memory associated with this inode */
drhd91c68f2010-05-14 14:52:25 +00001171 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1172 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001173#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001174 unsigned long long sharedByte; /* for AFP simulated shared lock */
1175#endif
drh6c7d5c52008-11-21 20:32:33 +00001176#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001177 sem_t *pSem; /* Named POSIX semaphore */
1178 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001179#endif
drhbbd42a62004-05-22 17:41:58 +00001180};
1181
drhda0e7682008-07-30 15:27:54 +00001182/*
drh8af6c222010-05-14 12:43:01 +00001183** A lists of all unixInodeInfo objects.
drh24efa542018-10-02 19:36:40 +00001184**
1185** Must hold unixBigLock in order to read or write this variable.
drhbbd42a62004-05-22 17:41:58 +00001186*/
drhc68886b2017-08-18 16:09:52 +00001187static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
drh095908e2018-08-13 20:46:18 +00001188
1189#ifdef SQLITE_DEBUG
1190/*
drh24efa542018-10-02 19:36:40 +00001191** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
1192** This routine is used only within assert() to help verify correct mutex
1193** usage.
drh095908e2018-08-13 20:46:18 +00001194*/
1195int unixFileMutexHeld(unixFile *pFile){
1196 assert( pFile->pInode );
1197 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1198}
1199int unixFileMutexNotheld(unixFile *pFile){
1200 assert( pFile->pInode );
1201 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1202}
1203#endif
drh5fdae772004-06-29 03:29:00 +00001204
drh5fdae772004-06-29 03:29:00 +00001205/*
dane18d4952011-02-21 11:46:24 +00001206**
drhaaeaa182015-11-24 15:12:47 +00001207** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001208** unixLogError().
1209**
1210** It is invoked after an error occurs in an OS function and errno has been
1211** set. It logs a message using sqlite3_log() containing the current value of
1212** errno and, if possible, the human-readable equivalent from strerror() or
1213** strerror_r().
1214**
1215** The first argument passed to the macro should be the error code that
1216** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1217** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001218** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001219** if any.
1220*/
drh0e9365c2011-03-02 02:08:13 +00001221#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1222static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001223 int errcode, /* SQLite error code */
1224 const char *zFunc, /* Name of OS function that failed */
1225 const char *zPath, /* File path associated with error */
1226 int iLine /* Source line number where error occurred */
1227){
1228 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001229 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001230
1231 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1232 ** the strerror() function to obtain the human-readable error message
1233 ** equivalent to errno. Otherwise, use strerror_r().
1234 */
1235#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1236 char aErr[80];
1237 memset(aErr, 0, sizeof(aErr));
1238 zErr = aErr;
1239
1240 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001241 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001242 ** returns a pointer to a buffer containing the error message. That pointer
1243 ** may point to aErr[], or it may point to some static storage somewhere.
1244 ** Otherwise, assume that the system provides the POSIX version of
1245 ** strerror_r(), which always writes an error message into aErr[].
1246 **
1247 ** If the code incorrectly assumes that it is the POSIX version that is
1248 ** available, the error message will often be an empty string. Not a
1249 ** huge problem. Incorrectly concluding that the GNU version is available
1250 ** could lead to a segfault though.
1251 */
1252#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1253 zErr =
1254# endif
drh0e9365c2011-03-02 02:08:13 +00001255 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001256
1257#elif SQLITE_THREADSAFE
1258 /* This is a threadsafe build, but strerror_r() is not available. */
1259 zErr = "";
1260#else
1261 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001262 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001263#endif
1264
drh0e9365c2011-03-02 02:08:13 +00001265 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001266 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001267 "os_unix.c:%d: (%d) %s(%s) - %s",
1268 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001269 );
1270
1271 return errcode;
1272}
1273
drh0e9365c2011-03-02 02:08:13 +00001274/*
1275** Close a file descriptor.
1276**
1277** We assume that close() almost always works, since it is only in a
1278** very sick application or on a very sick platform that it might fail.
1279** If it does fail, simply leak the file descriptor, but do log the
1280** error.
1281**
1282** Note that it is not safe to retry close() after EINTR since the
1283** file descriptor might have already been reused by another thread.
1284** So we don't even try to recover from an EINTR. Just log the error
1285** and move on.
1286*/
1287static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001288 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001289 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1290 pFile ? pFile->zPath : 0, lineno);
1291 }
1292}
dane18d4952011-02-21 11:46:24 +00001293
1294/*
drhe6d41732015-02-21 00:49:00 +00001295** Set the pFile->lastErrno. Do this in a subroutine as that provides
1296** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001297*/
1298static void storeLastErrno(unixFile *pFile, int error){
1299 pFile->lastErrno = error;
1300}
1301
1302/*
danb0ac3e32010-06-16 10:55:42 +00001303** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001304*/
drh0e9365c2011-03-02 02:08:13 +00001305static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001306 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001307 UnixUnusedFd *p;
1308 UnixUnusedFd *pNext;
drhef52b362018-08-13 22:50:34 +00001309 assert( unixFileMutexHeld(pFile) );
danb0ac3e32010-06-16 10:55:42 +00001310 for(p=pInode->pUnused; p; p=pNext){
1311 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001312 robust_close(pFile, p->fd, __LINE__);
1313 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001314 }
drh0e9365c2011-03-02 02:08:13 +00001315 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001316}
1317
1318/*
drh8af6c222010-05-14 12:43:01 +00001319** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001320**
drh24efa542018-10-02 19:36:40 +00001321** The global mutex must be held when this routine is called, but the mutex
1322** on the inode being deleted must NOT be held.
drh6c7d5c52008-11-21 20:32:33 +00001323*/
danb0ac3e32010-06-16 10:55:42 +00001324static void releaseInodeInfo(unixFile *pFile){
1325 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001326 assert( unixMutexHeld() );
drh095908e2018-08-13 20:46:18 +00001327 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00001328 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001329 pInode->nRef--;
1330 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001331 assert( pInode->pShmNode==0 );
drhef52b362018-08-13 22:50:34 +00001332 sqlite3_mutex_enter(pInode->pLockMutex);
danb0ac3e32010-06-16 10:55:42 +00001333 closePendingFds(pFile);
drhef52b362018-08-13 22:50:34 +00001334 sqlite3_mutex_leave(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001335 if( pInode->pPrev ){
1336 assert( pInode->pPrev->pNext==pInode );
1337 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001338 }else{
drh8af6c222010-05-14 12:43:01 +00001339 assert( inodeList==pInode );
1340 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001341 }
drh8af6c222010-05-14 12:43:01 +00001342 if( pInode->pNext ){
1343 assert( pInode->pNext->pPrev==pInode );
1344 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001345 }
drhda6dc242018-07-23 21:10:37 +00001346 sqlite3_mutex_free(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001347 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001348 }
drhbbd42a62004-05-22 17:41:58 +00001349 }
1350}
1351
1352/*
drh8af6c222010-05-14 12:43:01 +00001353** Given a file descriptor, locate the unixInodeInfo object that
1354** describes that file descriptor. Create a new one if necessary. The
1355** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001356**
drh24efa542018-10-02 19:36:40 +00001357** The global mutex must held when calling this routine.
dan9359c7b2009-08-21 08:29:10 +00001358**
drh6c7d5c52008-11-21 20:32:33 +00001359** Return an appropriate error code.
1360*/
drh8af6c222010-05-14 12:43:01 +00001361static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001362 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001363 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001364){
1365 int rc; /* System call return code */
1366 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001367 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1368 struct stat statbuf; /* Low-level file information */
1369 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001370
dan9359c7b2009-08-21 08:29:10 +00001371 assert( unixMutexHeld() );
1372
drh6c7d5c52008-11-21 20:32:33 +00001373 /* Get low-level information about the file that we can used to
1374 ** create a unique name for the file.
1375 */
1376 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001377 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001378 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001379 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001380#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001381 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1382#endif
1383 return SQLITE_IOERR;
1384 }
1385
drheb0d74f2009-02-03 15:27:02 +00001386#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001387 /* On OS X on an msdos filesystem, the inode number is reported
1388 ** incorrectly for zero-size files. See ticket #3260. To work
1389 ** around this problem (we consider it a bug in OS X, not SQLite)
1390 ** we always increase the file size to 1 by writing a single byte
1391 ** prior to accessing the inode number. The one byte written is
1392 ** an ASCII 'S' character which also happens to be the first byte
1393 ** in the header of every SQLite database. In this way, if there
1394 ** is a race condition such that another thread has already populated
1395 ** the first page of the database, no damage is done.
1396 */
drh7ed97b92010-01-20 13:07:21 +00001397 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001398 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001399 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001400 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001401 return SQLITE_IOERR;
1402 }
drh99ab3b12011-03-02 15:09:07 +00001403 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001404 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001405 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001406 return SQLITE_IOERR;
1407 }
1408 }
drheb0d74f2009-02-03 15:27:02 +00001409#endif
drh6c7d5c52008-11-21 20:32:33 +00001410
drh8af6c222010-05-14 12:43:01 +00001411 memset(&fileId, 0, sizeof(fileId));
1412 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001413#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001414 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001415#else
drh25ef7f52016-12-05 20:06:45 +00001416 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001417#endif
drh24efa542018-10-02 19:36:40 +00001418 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001419 pInode = inodeList;
1420 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1421 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001422 }
drh8af6c222010-05-14 12:43:01 +00001423 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001424 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001425 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001426 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001427 }
drh8af6c222010-05-14 12:43:01 +00001428 memset(pInode, 0, sizeof(*pInode));
1429 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
drh6886d6d2018-07-23 22:55:10 +00001430 if( sqlite3GlobalConfig.bCoreMutex ){
1431 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1432 if( pInode->pLockMutex==0 ){
1433 sqlite3_free(pInode);
1434 return SQLITE_NOMEM_BKPT;
1435 }
1436 }
drh8af6c222010-05-14 12:43:01 +00001437 pInode->nRef = 1;
drh24efa542018-10-02 19:36:40 +00001438 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001439 pInode->pNext = inodeList;
1440 pInode->pPrev = 0;
1441 if( inodeList ) inodeList->pPrev = pInode;
1442 inodeList = pInode;
1443 }else{
1444 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001445 }
drh8af6c222010-05-14 12:43:01 +00001446 *ppInode = pInode;
1447 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001448}
drh6c7d5c52008-11-21 20:32:33 +00001449
drhb959a012013-12-07 12:29:22 +00001450/*
1451** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1452*/
1453static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001454#if OS_VXWORKS
1455 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1456#else
drhb959a012013-12-07 12:29:22 +00001457 struct stat buf;
1458 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001459 (osStat(pFile->zPath, &buf)!=0
1460 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001461#endif
drhb959a012013-12-07 12:29:22 +00001462}
1463
aswift5b1a2562008-08-22 00:22:35 +00001464
1465/*
drhfbc7e882013-04-11 01:16:15 +00001466** Check a unixFile that is a database. Verify the following:
1467**
1468** (1) There is exactly one hard link on the file
1469** (2) The file is not a symbolic link
1470** (3) The file has not been renamed or unlinked
1471**
1472** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1473*/
1474static void verifyDbFile(unixFile *pFile){
1475 struct stat buf;
1476 int rc;
drh86151e82015-12-08 14:37:16 +00001477
1478 /* These verifications occurs for the main database only */
1479 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1480
drhfbc7e882013-04-11 01:16:15 +00001481 rc = osFstat(pFile->h, &buf);
1482 if( rc!=0 ){
1483 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001484 return;
1485 }
drh6369bc32016-03-21 16:06:42 +00001486 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001487 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001488 return;
1489 }
1490 if( buf.st_nlink>1 ){
1491 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001492 return;
1493 }
drhb959a012013-12-07 12:29:22 +00001494 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001495 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001496 return;
1497 }
1498}
1499
1500
1501/*
danielk197713adf8a2004-06-03 16:08:41 +00001502** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001503** file by this or any other process. If such a lock is held, set *pResOut
1504** to a non-zero value otherwise *pResOut is set to zero. The return value
1505** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001506*/
danielk1977861f7452008-06-05 11:39:11 +00001507static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001508 int rc = SQLITE_OK;
1509 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001510 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001511
danielk1977861f7452008-06-05 11:39:11 +00001512 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1513
drh054889e2005-11-30 03:20:31 +00001514 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001515 assert( pFile->eFileLock<=SHARED_LOCK );
drhda6dc242018-07-23 21:10:37 +00001516 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
danielk197713adf8a2004-06-03 16:08:41 +00001517
1518 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001519 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001520 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001521 }
1522
drh2ac3ee92004-06-07 16:27:46 +00001523 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001524 */
danielk197709480a92009-02-09 05:32:32 +00001525#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001526 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001527 struct flock lock;
1528 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001529 lock.l_start = RESERVED_BYTE;
1530 lock.l_len = 1;
1531 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001532 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1533 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001534 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001535 } else if( lock.l_type!=F_UNLCK ){
1536 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001537 }
1538 }
danielk197709480a92009-02-09 05:32:32 +00001539#endif
danielk197713adf8a2004-06-03 16:08:41 +00001540
drhda6dc242018-07-23 21:10:37 +00001541 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001542 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001543
aswift5b1a2562008-08-22 00:22:35 +00001544 *pResOut = reserved;
1545 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001546}
1547
drhddcfe922020-09-15 12:29:35 +00001548/* Forward declaration*/
1549static int unixSleep(sqlite3_vfs*,int);
1550
danielk197713adf8a2004-06-03 16:08:41 +00001551/*
drhf0119b22018-03-26 17:40:53 +00001552** Set a posix-advisory-lock.
1553**
1554** There are two versions of this routine. If compiled with
1555** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1556** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1557** value is set, then it is the number of milliseconds to wait before
1558** failing the lock. The iBusyTimeout value is always reset back to
1559** zero on each call.
1560**
1561** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1562** attempt to set the lock.
1563*/
1564#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1565# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1566#else
1567static int osSetPosixAdvisoryLock(
1568 int h, /* The file descriptor on which to take the lock */
1569 struct flock *pLock, /* The description of the lock */
1570 unixFile *pFile /* Structure holding timeout value */
1571){
dan7bb8b8a2020-05-06 20:27:18 +00001572 int tm = pFile->iBusyTimeout;
drhf0119b22018-03-26 17:40:53 +00001573 int rc = osFcntl(h,F_SETLK,pLock);
dan7bb8b8a2020-05-06 20:27:18 +00001574 while( rc<0 && tm>0 ){
drhf0119b22018-03-26 17:40:53 +00001575 /* On systems that support some kind of blocking file lock with a timeout,
1576 ** make appropriate changes here to invoke that blocking file lock. On
1577 ** generic posix, however, there is no such API. So we simply try the
1578 ** lock once every millisecond until either the timeout expires, or until
1579 ** the lock is obtained. */
drhddcfe922020-09-15 12:29:35 +00001580 unixSleep(0,1000);
drhfd725632018-03-26 20:43:05 +00001581 rc = osFcntl(h,F_SETLK,pLock);
dan7bb8b8a2020-05-06 20:27:18 +00001582 tm--;
drhf0119b22018-03-26 17:40:53 +00001583 }
1584 return rc;
1585}
1586#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1587
1588
1589/*
drha7e61d82011-03-12 17:02:57 +00001590** Attempt to set a system-lock on the file pFile. The lock is
1591** described by pLock.
1592**
drh77197112011-03-15 19:08:48 +00001593** If the pFile was opened read/write from unix-excl, then the only lock
1594** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001595** the first time any lock is attempted. All subsequent system locking
1596** operations become no-ops. Locking operations still happen internally,
1597** in order to coordinate access between separate database connections
1598** within this process, but all of that is handled in memory and the
1599** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001600**
1601** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1602** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1603** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001604**
1605** Zero is returned if the call completes successfully, or -1 if a call
1606** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001607*/
1608static int unixFileLock(unixFile *pFile, struct flock *pLock){
1609 int rc;
drh3cb93392011-03-12 18:10:44 +00001610 unixInodeInfo *pInode = pFile->pInode;
drh3cb93392011-03-12 18:10:44 +00001611 assert( pInode!=0 );
drhda6dc242018-07-23 21:10:37 +00001612 assert( sqlite3_mutex_held(pInode->pLockMutex) );
drh50358ad2015-12-02 01:04:33 +00001613 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001614 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001615 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001616 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001617 lock.l_whence = SEEK_SET;
1618 lock.l_start = SHARED_FIRST;
1619 lock.l_len = SHARED_SIZE;
1620 lock.l_type = F_WRLCK;
drhf0119b22018-03-26 17:40:53 +00001621 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
drha7e61d82011-03-12 17:02:57 +00001622 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001623 pInode->bProcessLock = 1;
1624 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001625 }else{
1626 rc = 0;
1627 }
1628 }else{
drhf0119b22018-03-26 17:40:53 +00001629 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
drha7e61d82011-03-12 17:02:57 +00001630 }
1631 return rc;
1632}
1633
1634/*
drh308c2a52010-05-14 11:30:18 +00001635** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001636** of the following:
1637**
drh2ac3ee92004-06-07 16:27:46 +00001638** (1) SHARED_LOCK
1639** (2) RESERVED_LOCK
1640** (3) PENDING_LOCK
1641** (4) EXCLUSIVE_LOCK
1642**
drhb3e04342004-06-08 00:47:47 +00001643** Sometimes when requesting one lock state, additional lock states
1644** are inserted in between. The locking might fail on one of the later
1645** transitions leaving the lock state different from what it started but
1646** still short of its goal. The following chart shows the allowed
1647** transitions and the inserted intermediate states:
1648**
1649** UNLOCKED -> SHARED
1650** SHARED -> RESERVED
1651** SHARED -> (PENDING) -> EXCLUSIVE
1652** RESERVED -> (PENDING) -> EXCLUSIVE
1653** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001654**
drha6abd042004-06-09 17:37:22 +00001655** This routine will only increase a lock. Use the sqlite3OsUnlock()
1656** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001657*/
drh308c2a52010-05-14 11:30:18 +00001658static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001659 /* The following describes the implementation of the various locks and
1660 ** lock transitions in terms of the POSIX advisory shared and exclusive
1661 ** lock primitives (called read-locks and write-locks below, to avoid
1662 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001663 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001664 ** accessing the same database file, in case that is ever required.
1665 **
1666 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1667 ** byte', each single bytes at well known offsets, and the 'shared byte
1668 ** range', a range of 510 bytes at a well known offset.
1669 **
1670 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001671 ** byte'. If this is successful, 'shared byte range' is read-locked
1672 ** and the lock on the 'pending byte' released. (Legacy note: When
1673 ** SQLite was first developed, Windows95 systems were still very common,
1674 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1675 ** single randomly selected by from the 'shared byte range' is locked.
1676 ** Windows95 is now pretty much extinct, but this work-around for the
1677 ** lack of shared-locks on Windows95 lives on, for backwards
1678 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001679 **
danielk197790ba3bd2004-06-25 08:32:25 +00001680 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1681 ** A RESERVED lock is implemented by grabbing a write-lock on the
1682 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001683 **
1684 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001685 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1686 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1687 ** obtained, but existing SHARED locks are allowed to persist. A process
1688 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1689 ** This property is used by the algorithm for rolling back a journal file
1690 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001691 **
danielk197790ba3bd2004-06-25 08:32:25 +00001692 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1693 ** implemented by obtaining a write-lock on the entire 'shared byte
1694 ** range'. Since all other locks require a read-lock on one of the bytes
1695 ** within this range, this ensures that no other locks are held on the
1696 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001697 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001698 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001699 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001700 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001701 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001702 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001703
drh054889e2005-11-30 03:20:31 +00001704 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001705 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1706 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001707 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001708 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001709
1710 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001711 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001712 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001713 */
drh308c2a52010-05-14 11:30:18 +00001714 if( pFile->eFileLock>=eFileLock ){
1715 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1716 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001717 return SQLITE_OK;
1718 }
1719
drh0c2694b2009-09-03 16:23:44 +00001720 /* Make sure the locking sequence is correct.
1721 ** (1) We never move from unlocked to anything higher than shared lock.
1722 ** (2) SQLite never explicitly requests a pendig lock.
1723 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001724 */
drh308c2a52010-05-14 11:30:18 +00001725 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1726 assert( eFileLock!=PENDING_LOCK );
1727 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001728
drh8af6c222010-05-14 12:43:01 +00001729 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001730 */
drh8af6c222010-05-14 12:43:01 +00001731 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001732 sqlite3_mutex_enter(pInode->pLockMutex);
drh029b44b2006-01-15 00:13:15 +00001733
danielk1977ad94b582007-08-20 06:44:22 +00001734 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001735 ** handle that precludes the requested lock, return BUSY.
1736 */
drh8af6c222010-05-14 12:43:01 +00001737 if( (pFile->eFileLock!=pInode->eFileLock &&
1738 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001739 ){
1740 rc = SQLITE_BUSY;
1741 goto end_lock;
1742 }
1743
1744 /* If a SHARED lock is requested, and some thread using this PID already
1745 ** has a SHARED or RESERVED lock, then increment reference counts and
1746 ** return SQLITE_OK.
1747 */
drh308c2a52010-05-14 11:30:18 +00001748 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001749 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001750 assert( eFileLock==SHARED_LOCK );
1751 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001752 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001753 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001754 pInode->nShared++;
1755 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001756 goto end_lock;
1757 }
1758
danielk19779a1d0ab2004-06-01 14:09:28 +00001759
drh3cde3bb2004-06-12 02:17:14 +00001760 /* A PENDING lock is needed before acquiring a SHARED lock and before
1761 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1762 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001763 */
drh0c2694b2009-09-03 16:23:44 +00001764 lock.l_len = 1L;
1765 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001766 if( eFileLock==SHARED_LOCK
1767 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001768 ){
drh308c2a52010-05-14 11:30:18 +00001769 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001770 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001771 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001772 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001773 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001774 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001775 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001776 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001777 goto end_lock;
1778 }
drh3cde3bb2004-06-12 02:17:14 +00001779 }
1780
1781
1782 /* If control gets to this point, then actually go ahead and make
1783 ** operating system calls for the specified lock.
1784 */
drh308c2a52010-05-14 11:30:18 +00001785 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001786 assert( pInode->nShared==0 );
1787 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001788 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001789
drh2ac3ee92004-06-07 16:27:46 +00001790 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001791 lock.l_start = SHARED_FIRST;
1792 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001793 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001794 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001795 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001796 }
dan661d71a2011-03-30 19:08:03 +00001797
drh2ac3ee92004-06-07 16:27:46 +00001798 /* Drop the temporary PENDING lock */
1799 lock.l_start = PENDING_BYTE;
1800 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001801 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001802 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1803 /* This could happen with a network mount */
1804 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001805 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001806 }
dan661d71a2011-03-30 19:08:03 +00001807
1808 if( rc ){
1809 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001810 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001811 }
dan661d71a2011-03-30 19:08:03 +00001812 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001813 }else{
drh308c2a52010-05-14 11:30:18 +00001814 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001815 pInode->nLock++;
1816 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001817 }
drh8af6c222010-05-14 12:43:01 +00001818 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001819 /* We are trying for an exclusive lock but another thread in this
1820 ** same process is still holding a shared lock. */
1821 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001822 }else{
drh3cde3bb2004-06-12 02:17:14 +00001823 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001824 ** assumed that there is a SHARED or greater lock on the file
1825 ** already.
1826 */
drh308c2a52010-05-14 11:30:18 +00001827 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001828 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001829
1830 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1831 if( eFileLock==RESERVED_LOCK ){
1832 lock.l_start = RESERVED_BYTE;
1833 lock.l_len = 1L;
1834 }else{
1835 lock.l_start = SHARED_FIRST;
1836 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001837 }
dan661d71a2011-03-30 19:08:03 +00001838
1839 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001840 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001841 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001842 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001843 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001844 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001845 }
drhbbd42a62004-05-22 17:41:58 +00001846 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001847
drh8f941bc2009-01-14 23:03:40 +00001848
drhd3d8c042012-05-29 17:02:40 +00001849#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001850 /* Set up the transaction-counter change checking flags when
1851 ** transitioning from a SHARED to a RESERVED lock. The change
1852 ** from SHARED to RESERVED marks the beginning of a normal
1853 ** write operation (not a hot journal rollback).
1854 */
1855 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001856 && pFile->eFileLock<=SHARED_LOCK
1857 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001858 ){
1859 pFile->transCntrChng = 0;
1860 pFile->dbUpdate = 0;
1861 pFile->inNormalWrite = 1;
1862 }
1863#endif
1864
1865
danielk1977ecb2a962004-06-02 06:30:16 +00001866 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001867 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001868 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001869 }else if( eFileLock==EXCLUSIVE_LOCK ){
1870 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001871 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001872 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001873
1874end_lock:
drhda6dc242018-07-23 21:10:37 +00001875 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001876 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1877 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001878 return rc;
1879}
1880
1881/*
dan08da86a2009-08-21 17:18:03 +00001882** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001883** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001884*/
1885static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001886 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001887 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drhef52b362018-08-13 22:50:34 +00001888 assert( unixFileMutexHeld(pFile) );
drh8af6c222010-05-14 12:43:01 +00001889 p->pNext = pInode->pUnused;
1890 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001891 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001892 pFile->pPreallocatedUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001893}
1894
1895/*
drh308c2a52010-05-14 11:30:18 +00001896** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001897** must be either NO_LOCK or SHARED_LOCK.
1898**
1899** If the locking level of the file descriptor is already at or below
1900** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001901**
1902** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1903** the byte range is divided into 2 parts and the first part is unlocked then
1904** set to a read lock, then the other part is simply unlocked. This works
1905** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1906** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001907*/
drha7e61d82011-03-12 17:02:57 +00001908static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001909 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001910 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001911 struct flock lock;
1912 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001913
drh054889e2005-11-30 03:20:31 +00001914 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001915 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001916 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001917 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001918
drh308c2a52010-05-14 11:30:18 +00001919 assert( eFileLock<=SHARED_LOCK );
1920 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001921 return SQLITE_OK;
1922 }
drh8af6c222010-05-14 12:43:01 +00001923 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001924 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001925 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001926 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001927 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001928
drhd3d8c042012-05-29 17:02:40 +00001929#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001930 /* When reducing a lock such that other processes can start
1931 ** reading the database file again, make sure that the
1932 ** transaction counter was updated if any part of the database
1933 ** file changed. If the transaction counter is not updated,
1934 ** other connections to the same file might not realize that
1935 ** the file has changed and hence might not know to flush their
1936 ** cache. The use of a stale cache can lead to database corruption.
1937 */
drh8f941bc2009-01-14 23:03:40 +00001938 pFile->inNormalWrite = 0;
1939#endif
1940
drh7ed97b92010-01-20 13:07:21 +00001941 /* downgrading to a shared lock on NFS involves clearing the write lock
1942 ** before establishing the readlock - to avoid a race condition we downgrade
1943 ** the lock in 2 blocks, so that part of the range will be covered by a
1944 ** write lock until the rest is covered by a read lock:
1945 ** 1: [WWWWW]
1946 ** 2: [....W]
1947 ** 3: [RRRRW]
1948 ** 4: [RRRR.]
1949 */
drh308c2a52010-05-14 11:30:18 +00001950 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001951#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001952 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001953 assert( handleNFSUnlock==0 );
1954#endif
1955#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001956 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001957 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001958 off_t divSize = SHARED_SIZE - 1;
1959
1960 lock.l_type = F_UNLCK;
1961 lock.l_whence = SEEK_SET;
1962 lock.l_start = SHARED_FIRST;
1963 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001964 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001965 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001966 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001967 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001968 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001969 }
drh7ed97b92010-01-20 13:07:21 +00001970 lock.l_type = F_RDLCK;
1971 lock.l_whence = SEEK_SET;
1972 lock.l_start = SHARED_FIRST;
1973 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001974 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001975 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001976 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1977 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001978 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001979 }
1980 goto end_unlock;
1981 }
1982 lock.l_type = F_UNLCK;
1983 lock.l_whence = SEEK_SET;
1984 lock.l_start = SHARED_FIRST+divSize;
1985 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001986 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001987 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001988 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001989 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001990 goto end_unlock;
1991 }
drh30f776f2011-02-25 03:25:07 +00001992 }else
1993#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1994 {
drh7ed97b92010-01-20 13:07:21 +00001995 lock.l_type = F_RDLCK;
1996 lock.l_whence = SEEK_SET;
1997 lock.l_start = SHARED_FIRST;
1998 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001999 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00002000 /* In theory, the call to unixFileLock() cannot fail because another
2001 ** process is holding an incompatible lock. If it does, this
2002 ** indicates that the other process is not following the locking
2003 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
2004 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2005 ** an assert to fail). */
2006 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002007 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00002008 goto end_unlock;
2009 }
drh9c105bb2004-10-02 20:38:28 +00002010 }
2011 }
drhbbd42a62004-05-22 17:41:58 +00002012 lock.l_type = F_UNLCK;
2013 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00002014 lock.l_start = PENDING_BYTE;
2015 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00002016 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002017 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002018 }else{
danea83bc62011-04-01 11:56:32 +00002019 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002020 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00002021 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00002022 }
drhbbd42a62004-05-22 17:41:58 +00002023 }
drh308c2a52010-05-14 11:30:18 +00002024 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00002025 /* Decrement the shared lock counter. Release the lock using an
2026 ** OS call only when all threads in this same process have released
2027 ** the lock.
2028 */
drh8af6c222010-05-14 12:43:01 +00002029 pInode->nShared--;
2030 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00002031 lock.l_type = F_UNLCK;
2032 lock.l_whence = SEEK_SET;
2033 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00002034 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002035 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002036 }else{
danea83bc62011-04-01 11:56:32 +00002037 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002038 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00002039 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002040 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002041 }
drha6abd042004-06-09 17:37:22 +00002042 }
2043
drhbbd42a62004-05-22 17:41:58 +00002044 /* Decrement the count of locks against this same file. When the
2045 ** count reaches zero, close any other file descriptors whose close
2046 ** was deferred because of outstanding locks.
2047 */
drh8af6c222010-05-14 12:43:01 +00002048 pInode->nLock--;
2049 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00002050 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00002051 }
drhf2f105d2012-08-20 15:53:54 +00002052
aswift5b1a2562008-08-22 00:22:35 +00002053end_unlock:
drhda6dc242018-07-23 21:10:37 +00002054 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00002055 if( rc==SQLITE_OK ){
2056 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00002057 }
drh9c105bb2004-10-02 20:38:28 +00002058 return rc;
drhbbd42a62004-05-22 17:41:58 +00002059}
2060
2061/*
drh308c2a52010-05-14 11:30:18 +00002062** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002063** must be either NO_LOCK or SHARED_LOCK.
2064**
2065** If the locking level of the file descriptor is already at or below
2066** the requested locking level, this routine is a no-op.
2067*/
drh308c2a52010-05-14 11:30:18 +00002068static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00002069#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00002070 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00002071#endif
drha7e61d82011-03-12 17:02:57 +00002072 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00002073}
2074
mistachkine98844f2013-08-24 00:59:24 +00002075#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002076static int unixMapfile(unixFile *pFd, i64 nByte);
2077static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00002078#endif
danf23da962013-03-23 21:00:41 +00002079
drh7ed97b92010-01-20 13:07:21 +00002080/*
danielk1977e339d652008-06-28 11:23:00 +00002081** This function performs the parts of the "close file" operation
2082** common to all locking schemes. It closes the directory and file
2083** handles, if they are valid, and sets all fields of the unixFile
2084** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00002085**
2086** It is *not* necessary to hold the mutex when this routine is called,
2087** even on VxWorks. A mutex will be acquired on VxWorks by the
2088** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00002089*/
2090static int closeUnixFile(sqlite3_file *id){
2091 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00002092#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002093 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00002094#endif
dan661d71a2011-03-30 19:08:03 +00002095 if( pFile->h>=0 ){
2096 robust_close(pFile, pFile->h, __LINE__);
2097 pFile->h = -1;
2098 }
2099#if OS_VXWORKS
2100 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00002101 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00002102 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00002103 }
2104 vxworksReleaseFileId(pFile->pId);
2105 pFile->pId = 0;
2106 }
2107#endif
drh0bdbc902014-06-16 18:35:06 +00002108#ifdef SQLITE_UNLINK_AFTER_CLOSE
2109 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2110 osUnlink(pFile->zPath);
2111 sqlite3_free(*(char**)&pFile->zPath);
2112 pFile->zPath = 0;
2113 }
2114#endif
dan661d71a2011-03-30 19:08:03 +00002115 OSTRACE(("CLOSE %-3d\n", pFile->h));
2116 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00002117 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00002118 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00002119 return SQLITE_OK;
2120}
2121
2122/*
danielk1977e3026632004-06-22 11:29:02 +00002123** Close a file.
2124*/
danielk197762079062007-08-15 17:08:46 +00002125static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002126 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002127 unixFile *pFile = (unixFile *)id;
drhef52b362018-08-13 22:50:34 +00002128 unixInodeInfo *pInode = pFile->pInode;
2129
2130 assert( pInode!=0 );
drhfbc7e882013-04-11 01:16:15 +00002131 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002132 unixUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00002133 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00002134 unixEnterMutex();
2135
2136 /* unixFile.pInode is always valid here. Otherwise, a different close
2137 ** routine (e.g. nolockClose()) would be called instead.
2138 */
2139 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
drhef52b362018-08-13 22:50:34 +00002140 sqlite3_mutex_enter(pInode->pLockMutex);
drh3fcef1a2018-08-16 16:24:24 +00002141 if( pInode->nLock ){
dan661d71a2011-03-30 19:08:03 +00002142 /* If there are outstanding locks, do not actually close the file just
2143 ** yet because that would clear those locks. Instead, add the file
2144 ** descriptor to pInode->pUnused list. It will be automatically closed
2145 ** when the last lock is cleared.
2146 */
2147 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002148 }
drhef52b362018-08-13 22:50:34 +00002149 sqlite3_mutex_leave(pInode->pLockMutex);
dan661d71a2011-03-30 19:08:03 +00002150 releaseInodeInfo(pFile);
dan2b06b072020-09-04 17:30:59 +00002151 assert( pFile->pShm==0 );
dan661d71a2011-03-30 19:08:03 +00002152 rc = closeUnixFile(id);
2153 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002154 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002155}
2156
drh734c9862008-11-28 15:37:20 +00002157/************** End of the posix advisory lock implementation *****************
2158******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002159
drh734c9862008-11-28 15:37:20 +00002160/******************************************************************************
2161****************************** No-op Locking **********************************
2162**
2163** Of the various locking implementations available, this is by far the
2164** simplest: locking is ignored. No attempt is made to lock the database
2165** file for reading or writing.
2166**
2167** This locking mode is appropriate for use on read-only databases
2168** (ex: databases that are burned into CD-ROM, for example.) It can
2169** also be used if the application employs some external mechanism to
2170** prevent simultaneous access of the same database by two or more
2171** database connections. But there is a serious risk of database
2172** corruption if this locking mode is used in situations where multiple
2173** database connections are accessing the same database file at the same
2174** time and one or more of those connections are writing.
2175*/
drhbfe66312006-10-03 17:40:40 +00002176
drh734c9862008-11-28 15:37:20 +00002177static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2178 UNUSED_PARAMETER(NotUsed);
2179 *pResOut = 0;
2180 return SQLITE_OK;
2181}
drh734c9862008-11-28 15:37:20 +00002182static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2183 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2184 return SQLITE_OK;
2185}
drh734c9862008-11-28 15:37:20 +00002186static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2187 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2188 return SQLITE_OK;
2189}
2190
2191/*
drh9b35ea62008-11-29 02:20:26 +00002192** Close the file.
drh734c9862008-11-28 15:37:20 +00002193*/
2194static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002195 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002196}
2197
2198/******************* End of the no-op lock implementation *********************
2199******************************************************************************/
2200
2201/******************************************************************************
2202************************* Begin dot-file Locking ******************************
2203**
mistachkin48864df2013-03-21 21:20:32 +00002204** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002205** files (really a directory) to control access to the database. This works
2206** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002207**
2208** (1) There is zero concurrency. A single reader blocks all other
2209** connections from reading or writing the database.
2210**
2211** (2) An application crash or power loss can leave stale lock files
2212** sitting around that need to be cleared manually.
2213**
2214** Nevertheless, a dotlock is an appropriate locking mode for use if no
2215** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002216**
drh9ef6bc42011-11-04 02:24:02 +00002217** Dotfile locking works by creating a subdirectory in the same directory as
2218** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002219** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002220** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002221*/
2222
2223/*
2224** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002225** lock directory.
drh734c9862008-11-28 15:37:20 +00002226*/
2227#define DOTLOCK_SUFFIX ".lock"
2228
drh7708e972008-11-29 00:56:52 +00002229/*
2230** This routine checks if there is a RESERVED lock held on the specified
2231** file by this or any other process. If such a lock is held, set *pResOut
2232** to a non-zero value otherwise *pResOut is set to zero. The return value
2233** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2234**
2235** In dotfile locking, either a lock exists or it does not. So in this
2236** variation of CheckReservedLock(), *pResOut is set to true if any lock
2237** is held on the file and false if the file is unlocked.
2238*/
drh734c9862008-11-28 15:37:20 +00002239static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2240 int rc = SQLITE_OK;
2241 int reserved = 0;
2242 unixFile *pFile = (unixFile*)id;
2243
2244 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2245
2246 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002247 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002248 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002249 *pResOut = reserved;
2250 return rc;
2251}
2252
drh7708e972008-11-29 00:56:52 +00002253/*
drh308c2a52010-05-14 11:30:18 +00002254** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002255** of the following:
2256**
2257** (1) SHARED_LOCK
2258** (2) RESERVED_LOCK
2259** (3) PENDING_LOCK
2260** (4) EXCLUSIVE_LOCK
2261**
2262** Sometimes when requesting one lock state, additional lock states
2263** are inserted in between. The locking might fail on one of the later
2264** transitions leaving the lock state different from what it started but
2265** still short of its goal. The following chart shows the allowed
2266** transitions and the inserted intermediate states:
2267**
2268** UNLOCKED -> SHARED
2269** SHARED -> RESERVED
2270** SHARED -> (PENDING) -> EXCLUSIVE
2271** RESERVED -> (PENDING) -> EXCLUSIVE
2272** PENDING -> EXCLUSIVE
2273**
2274** This routine will only increase a lock. Use the sqlite3OsUnlock()
2275** routine to lower a locking level.
2276**
2277** With dotfile locking, we really only support state (4): EXCLUSIVE.
2278** But we track the other locking levels internally.
2279*/
drh308c2a52010-05-14 11:30:18 +00002280static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002281 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002282 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002283 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002284
drh7708e972008-11-29 00:56:52 +00002285
2286 /* If we have any lock, then the lock file already exists. All we have
2287 ** to do is adjust our internal record of the lock level.
2288 */
drh308c2a52010-05-14 11:30:18 +00002289 if( pFile->eFileLock > NO_LOCK ){
2290 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002291 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002292#ifdef HAVE_UTIME
2293 utime(zLockFile, NULL);
2294#else
drh734c9862008-11-28 15:37:20 +00002295 utimes(zLockFile, NULL);
2296#endif
drh7708e972008-11-29 00:56:52 +00002297 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002298 }
2299
2300 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002301 rc = osMkdir(zLockFile, 0777);
2302 if( rc<0 ){
2303 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002304 int tErrno = errno;
2305 if( EEXIST == tErrno ){
2306 rc = SQLITE_BUSY;
2307 } else {
2308 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002309 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002310 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002311 }
2312 }
drh7708e972008-11-29 00:56:52 +00002313 return rc;
drh734c9862008-11-28 15:37:20 +00002314 }
drh734c9862008-11-28 15:37:20 +00002315
2316 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002317 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002318 return rc;
2319}
2320
drh7708e972008-11-29 00:56:52 +00002321/*
drh308c2a52010-05-14 11:30:18 +00002322** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002323** must be either NO_LOCK or SHARED_LOCK.
2324**
2325** If the locking level of the file descriptor is already at or below
2326** the requested locking level, this routine is a no-op.
2327**
2328** When the locking level reaches NO_LOCK, delete the lock file.
2329*/
drh308c2a52010-05-14 11:30:18 +00002330static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002331 unixFile *pFile = (unixFile*)id;
2332 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002333 int rc;
drh734c9862008-11-28 15:37:20 +00002334
2335 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002336 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002337 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002338 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002339
2340 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002341 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002342 return SQLITE_OK;
2343 }
drh7708e972008-11-29 00:56:52 +00002344
2345 /* To downgrade to shared, simply update our internal notion of the
2346 ** lock state. No need to mess with the file on disk.
2347 */
drh308c2a52010-05-14 11:30:18 +00002348 if( eFileLock==SHARED_LOCK ){
2349 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002350 return SQLITE_OK;
2351 }
2352
drh7708e972008-11-29 00:56:52 +00002353 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002354 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002355 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002356 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002357 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002358 if( tErrno==ENOENT ){
2359 rc = SQLITE_OK;
2360 }else{
danea83bc62011-04-01 11:56:32 +00002361 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002362 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002363 }
2364 return rc;
2365 }
drh308c2a52010-05-14 11:30:18 +00002366 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002367 return SQLITE_OK;
2368}
2369
2370/*
drh9b35ea62008-11-29 02:20:26 +00002371** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002372*/
2373static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002374 unixFile *pFile = (unixFile*)id;
2375 assert( id!=0 );
2376 dotlockUnlock(id, NO_LOCK);
2377 sqlite3_free(pFile->lockingContext);
2378 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002379}
2380/****************** End of the dot-file lock implementation *******************
2381******************************************************************************/
2382
2383/******************************************************************************
2384************************** Begin flock Locking ********************************
2385**
2386** Use the flock() system call to do file locking.
2387**
drh6b9d6dd2008-12-03 19:34:47 +00002388** flock() locking is like dot-file locking in that the various
2389** fine-grain locking levels supported by SQLite are collapsed into
2390** a single exclusive lock. In other words, SHARED, RESERVED, and
2391** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2392** still works when you do this, but concurrency is reduced since
2393** only a single process can be reading the database at a time.
2394**
drhe89b2912015-03-03 20:42:01 +00002395** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002396*/
drhe89b2912015-03-03 20:42:01 +00002397#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002398
drh6b9d6dd2008-12-03 19:34:47 +00002399/*
drhff812312011-02-23 13:33:46 +00002400** Retry flock() calls that fail with EINTR
2401*/
2402#ifdef EINTR
2403static int robust_flock(int fd, int op){
2404 int rc;
2405 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2406 return rc;
2407}
2408#else
drh5c819272011-02-23 14:00:12 +00002409# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002410#endif
2411
2412
2413/*
drh6b9d6dd2008-12-03 19:34:47 +00002414** This routine checks if there is a RESERVED lock held on the specified
2415** file by this or any other process. If such a lock is held, set *pResOut
2416** to a non-zero value otherwise *pResOut is set to zero. The return value
2417** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2418*/
drh734c9862008-11-28 15:37:20 +00002419static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2420 int rc = SQLITE_OK;
2421 int reserved = 0;
2422 unixFile *pFile = (unixFile*)id;
2423
2424 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2425
2426 assert( pFile );
2427
2428 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002429 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002430 reserved = 1;
2431 }
2432
2433 /* Otherwise see if some other process holds it. */
2434 if( !reserved ){
2435 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002436 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002437 if( !lrc ){
2438 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002439 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002440 if ( lrc ) {
2441 int tErrno = errno;
2442 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002443 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002444 storeLastErrno(pFile, tErrno);
2445 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002446 }
2447 } else {
2448 int tErrno = errno;
2449 reserved = 1;
2450 /* someone else might have it reserved */
2451 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2452 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002453 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002454 rc = lrc;
2455 }
2456 }
2457 }
drh308c2a52010-05-14 11:30:18 +00002458 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002459
2460#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002461 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002462 rc = SQLITE_OK;
2463 reserved=1;
2464 }
2465#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2466 *pResOut = reserved;
2467 return rc;
2468}
2469
drh6b9d6dd2008-12-03 19:34:47 +00002470/*
drh308c2a52010-05-14 11:30:18 +00002471** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002472** of the following:
2473**
2474** (1) SHARED_LOCK
2475** (2) RESERVED_LOCK
2476** (3) PENDING_LOCK
2477** (4) EXCLUSIVE_LOCK
2478**
2479** Sometimes when requesting one lock state, additional lock states
2480** are inserted in between. The locking might fail on one of the later
2481** transitions leaving the lock state different from what it started but
2482** still short of its goal. The following chart shows the allowed
2483** transitions and the inserted intermediate states:
2484**
2485** UNLOCKED -> SHARED
2486** SHARED -> RESERVED
2487** SHARED -> (PENDING) -> EXCLUSIVE
2488** RESERVED -> (PENDING) -> EXCLUSIVE
2489** PENDING -> EXCLUSIVE
2490**
2491** flock() only really support EXCLUSIVE locks. We track intermediate
2492** lock states in the sqlite3_file structure, but all locks SHARED or
2493** above are really EXCLUSIVE locks and exclude all other processes from
2494** access the file.
2495**
2496** This routine will only increase a lock. Use the sqlite3OsUnlock()
2497** routine to lower a locking level.
2498*/
drh308c2a52010-05-14 11:30:18 +00002499static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002500 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002501 unixFile *pFile = (unixFile*)id;
2502
2503 assert( pFile );
2504
2505 /* if we already have a lock, it is exclusive.
2506 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002507 if (pFile->eFileLock > NO_LOCK) {
2508 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002509 return SQLITE_OK;
2510 }
2511
2512 /* grab an exclusive lock */
2513
drhff812312011-02-23 13:33:46 +00002514 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002515 int tErrno = errno;
2516 /* didn't get, must be busy */
2517 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2518 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002519 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002520 }
2521 } else {
2522 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002523 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002524 }
drh308c2a52010-05-14 11:30:18 +00002525 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2526 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002527#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002528 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002529 rc = SQLITE_BUSY;
2530 }
2531#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2532 return rc;
2533}
2534
drh6b9d6dd2008-12-03 19:34:47 +00002535
2536/*
drh308c2a52010-05-14 11:30:18 +00002537** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002538** must be either NO_LOCK or SHARED_LOCK.
2539**
2540** If the locking level of the file descriptor is already at or below
2541** the requested locking level, this routine is a no-op.
2542*/
drh308c2a52010-05-14 11:30:18 +00002543static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002544 unixFile *pFile = (unixFile*)id;
2545
2546 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002547 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002548 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002549 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002550
2551 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002552 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002553 return SQLITE_OK;
2554 }
2555
2556 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002557 if (eFileLock==SHARED_LOCK) {
2558 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002559 return SQLITE_OK;
2560 }
2561
2562 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002563 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002564#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002565 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002566#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002567 return SQLITE_IOERR_UNLOCK;
2568 }else{
drh308c2a52010-05-14 11:30:18 +00002569 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002570 return SQLITE_OK;
2571 }
2572}
2573
2574/*
2575** Close a file.
2576*/
2577static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002578 assert( id!=0 );
2579 flockUnlock(id, NO_LOCK);
2580 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002581}
2582
2583#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2584
2585/******************* End of the flock lock implementation *********************
2586******************************************************************************/
2587
2588/******************************************************************************
2589************************ Begin Named Semaphore Locking ************************
2590**
2591** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002592**
2593** Semaphore locking is like dot-lock and flock in that it really only
2594** supports EXCLUSIVE locking. Only a single process can read or write
2595** the database file at a time. This reduces potential concurrency, but
2596** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002597*/
2598#if OS_VXWORKS
2599
drh6b9d6dd2008-12-03 19:34:47 +00002600/*
2601** This routine checks if there is a RESERVED lock held on the specified
2602** file by this or any other process. If such a lock is held, set *pResOut
2603** to a non-zero value otherwise *pResOut is set to zero. The return value
2604** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2605*/
drh8cd5b252015-03-02 22:06:43 +00002606static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002607 int rc = SQLITE_OK;
2608 int reserved = 0;
2609 unixFile *pFile = (unixFile*)id;
2610
2611 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2612
2613 assert( pFile );
2614
2615 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002616 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002617 reserved = 1;
2618 }
2619
2620 /* Otherwise see if some other process holds it. */
2621 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002622 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002623
2624 if( sem_trywait(pSem)==-1 ){
2625 int tErrno = errno;
2626 if( EAGAIN != tErrno ){
2627 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002628 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002629 } else {
2630 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002631 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002632 }
2633 }else{
2634 /* we could have it if we want it */
2635 sem_post(pSem);
2636 }
2637 }
drh308c2a52010-05-14 11:30:18 +00002638 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002639
2640 *pResOut = reserved;
2641 return rc;
2642}
2643
drh6b9d6dd2008-12-03 19:34:47 +00002644/*
drh308c2a52010-05-14 11:30:18 +00002645** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002646** of the following:
2647**
2648** (1) SHARED_LOCK
2649** (2) RESERVED_LOCK
2650** (3) PENDING_LOCK
2651** (4) EXCLUSIVE_LOCK
2652**
2653** Sometimes when requesting one lock state, additional lock states
2654** are inserted in between. The locking might fail on one of the later
2655** transitions leaving the lock state different from what it started but
2656** still short of its goal. The following chart shows the allowed
2657** transitions and the inserted intermediate states:
2658**
2659** UNLOCKED -> SHARED
2660** SHARED -> RESERVED
2661** SHARED -> (PENDING) -> EXCLUSIVE
2662** RESERVED -> (PENDING) -> EXCLUSIVE
2663** PENDING -> EXCLUSIVE
2664**
2665** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2666** lock states in the sqlite3_file structure, but all locks SHARED or
2667** above are really EXCLUSIVE locks and exclude all other processes from
2668** access the file.
2669**
2670** This routine will only increase a lock. Use the sqlite3OsUnlock()
2671** routine to lower a locking level.
2672*/
drh8cd5b252015-03-02 22:06:43 +00002673static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002674 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002675 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002676 int rc = SQLITE_OK;
2677
2678 /* if we already have a lock, it is exclusive.
2679 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002680 if (pFile->eFileLock > NO_LOCK) {
2681 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002682 rc = SQLITE_OK;
2683 goto sem_end_lock;
2684 }
2685
2686 /* lock semaphore now but bail out when already locked. */
2687 if( sem_trywait(pSem)==-1 ){
2688 rc = SQLITE_BUSY;
2689 goto sem_end_lock;
2690 }
2691
2692 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002693 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002694
2695 sem_end_lock:
2696 return rc;
2697}
2698
drh6b9d6dd2008-12-03 19:34:47 +00002699/*
drh308c2a52010-05-14 11:30:18 +00002700** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002701** must be either NO_LOCK or SHARED_LOCK.
2702**
2703** If the locking level of the file descriptor is already at or below
2704** the requested locking level, this routine is a no-op.
2705*/
drh8cd5b252015-03-02 22:06:43 +00002706static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002707 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002708 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002709
2710 assert( pFile );
2711 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002712 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002713 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002714 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002715
2716 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002717 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002718 return SQLITE_OK;
2719 }
2720
2721 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002722 if (eFileLock==SHARED_LOCK) {
2723 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002724 return SQLITE_OK;
2725 }
2726
2727 /* no, really unlock. */
2728 if ( sem_post(pSem)==-1 ) {
2729 int rc, tErrno = errno;
2730 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2731 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002732 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002733 }
2734 return rc;
2735 }
drh308c2a52010-05-14 11:30:18 +00002736 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002737 return SQLITE_OK;
2738}
2739
2740/*
2741 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002742 */
drh8cd5b252015-03-02 22:06:43 +00002743static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002744 if( id ){
2745 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002746 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002747 assert( pFile );
drh095908e2018-08-13 20:46:18 +00002748 assert( unixFileMutexNotheld(pFile) );
drh734c9862008-11-28 15:37:20 +00002749 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002750 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002751 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002752 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002753 }
2754 return SQLITE_OK;
2755}
2756
2757#endif /* OS_VXWORKS */
2758/*
2759** Named semaphore locking is only available on VxWorks.
2760**
2761*************** End of the named semaphore lock implementation ****************
2762******************************************************************************/
2763
2764
2765/******************************************************************************
2766*************************** Begin AFP Locking *********************************
2767**
2768** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2769** on Apple Macintosh computers - both OS9 and OSX.
2770**
2771** Third-party implementations of AFP are available. But this code here
2772** only works on OSX.
2773*/
2774
drhd2cb50b2009-01-09 21:41:17 +00002775#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002776/*
2777** The afpLockingContext structure contains all afp lock specific state
2778*/
drhbfe66312006-10-03 17:40:40 +00002779typedef struct afpLockingContext afpLockingContext;
2780struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002781 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002782 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002783};
2784
2785struct ByteRangeLockPB2
2786{
2787 unsigned long long offset; /* offset to first byte to lock */
2788 unsigned long long length; /* nbr of bytes to lock */
2789 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2790 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2791 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2792 int fd; /* file desc to assoc this lock with */
2793};
2794
drhfd131da2007-08-07 17:13:03 +00002795#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002796
drh6b9d6dd2008-12-03 19:34:47 +00002797/*
2798** This is a utility for setting or clearing a bit-range lock on an
2799** AFP filesystem.
2800**
2801** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2802*/
2803static int afpSetLock(
2804 const char *path, /* Name of the file to be locked or unlocked */
2805 unixFile *pFile, /* Open file descriptor on path */
2806 unsigned long long offset, /* First byte to be locked */
2807 unsigned long long length, /* Number of bytes to lock */
2808 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002809){
drh6b9d6dd2008-12-03 19:34:47 +00002810 struct ByteRangeLockPB2 pb;
2811 int err;
drhbfe66312006-10-03 17:40:40 +00002812
2813 pb.unLockFlag = setLockFlag ? 0 : 1;
2814 pb.startEndFlag = 0;
2815 pb.offset = offset;
2816 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002817 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002818
drh308c2a52010-05-14 11:30:18 +00002819 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002820 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002821 offset, length));
drhbfe66312006-10-03 17:40:40 +00002822 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2823 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002824 int rc;
2825 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002826 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2827 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002828#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2829 rc = SQLITE_BUSY;
2830#else
drh734c9862008-11-28 15:37:20 +00002831 rc = sqliteErrorFromPosixError(tErrno,
2832 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002833#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002834 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002835 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002836 }
2837 return rc;
drhbfe66312006-10-03 17:40:40 +00002838 } else {
aswift5b1a2562008-08-22 00:22:35 +00002839 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002840 }
2841}
2842
drh6b9d6dd2008-12-03 19:34:47 +00002843/*
2844** This routine checks if there is a RESERVED lock held on the specified
2845** file by this or any other process. If such a lock is held, set *pResOut
2846** to a non-zero value otherwise *pResOut is set to zero. The return value
2847** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2848*/
danielk1977e339d652008-06-28 11:23:00 +00002849static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002850 int rc = SQLITE_OK;
2851 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002852 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002853 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002854
aswift5b1a2562008-08-22 00:22:35 +00002855 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2856
2857 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002858 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002859 if( context->reserved ){
2860 *pResOut = 1;
2861 return SQLITE_OK;
2862 }
drhda6dc242018-07-23 21:10:37 +00002863 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
drhbfe66312006-10-03 17:40:40 +00002864 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002865 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002866 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002867 }
2868
2869 /* Otherwise see if some other process holds it.
2870 */
aswift5b1a2562008-08-22 00:22:35 +00002871 if( !reserved ){
2872 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002873 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002874 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002875 /* if we succeeded in taking the reserved lock, unlock it to restore
2876 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002877 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002878 } else {
2879 /* if we failed to get the lock then someone else must have it */
2880 reserved = 1;
2881 }
2882 if( IS_LOCK_ERROR(lrc) ){
2883 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002884 }
2885 }
drhbfe66312006-10-03 17:40:40 +00002886
drhda6dc242018-07-23 21:10:37 +00002887 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00002888 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002889
2890 *pResOut = reserved;
2891 return rc;
drhbfe66312006-10-03 17:40:40 +00002892}
2893
drh6b9d6dd2008-12-03 19:34:47 +00002894/*
drh308c2a52010-05-14 11:30:18 +00002895** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002896** of the following:
2897**
2898** (1) SHARED_LOCK
2899** (2) RESERVED_LOCK
2900** (3) PENDING_LOCK
2901** (4) EXCLUSIVE_LOCK
2902**
2903** Sometimes when requesting one lock state, additional lock states
2904** are inserted in between. The locking might fail on one of the later
2905** transitions leaving the lock state different from what it started but
2906** still short of its goal. The following chart shows the allowed
2907** transitions and the inserted intermediate states:
2908**
2909** UNLOCKED -> SHARED
2910** SHARED -> RESERVED
2911** SHARED -> (PENDING) -> EXCLUSIVE
2912** RESERVED -> (PENDING) -> EXCLUSIVE
2913** PENDING -> EXCLUSIVE
2914**
2915** This routine will only increase a lock. Use the sqlite3OsUnlock()
2916** routine to lower a locking level.
2917*/
drh308c2a52010-05-14 11:30:18 +00002918static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002919 int rc = SQLITE_OK;
2920 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002921 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002922 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002923
2924 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002925 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2926 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002927 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002928
drhbfe66312006-10-03 17:40:40 +00002929 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002930 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002931 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002932 */
drh308c2a52010-05-14 11:30:18 +00002933 if( pFile->eFileLock>=eFileLock ){
2934 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2935 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002936 return SQLITE_OK;
2937 }
2938
2939 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002940 ** (1) We never move from unlocked to anything higher than shared lock.
2941 ** (2) SQLite never explicitly requests a pendig lock.
2942 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002943 */
drh308c2a52010-05-14 11:30:18 +00002944 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2945 assert( eFileLock!=PENDING_LOCK );
2946 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002947
drh8af6c222010-05-14 12:43:01 +00002948 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002949 */
drh8af6c222010-05-14 12:43:01 +00002950 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00002951 sqlite3_mutex_enter(pInode->pLockMutex);
drh7ed97b92010-01-20 13:07:21 +00002952
2953 /* If some thread using this PID has a lock via a different unixFile*
2954 ** handle that precludes the requested lock, return BUSY.
2955 */
drh8af6c222010-05-14 12:43:01 +00002956 if( (pFile->eFileLock!=pInode->eFileLock &&
2957 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002958 ){
2959 rc = SQLITE_BUSY;
2960 goto afp_end_lock;
2961 }
2962
2963 /* If a SHARED lock is requested, and some thread using this PID already
2964 ** has a SHARED or RESERVED lock, then increment reference counts and
2965 ** return SQLITE_OK.
2966 */
drh308c2a52010-05-14 11:30:18 +00002967 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002968 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002969 assert( eFileLock==SHARED_LOCK );
2970 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002971 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002972 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002973 pInode->nShared++;
2974 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002975 goto afp_end_lock;
2976 }
drhbfe66312006-10-03 17:40:40 +00002977
2978 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002979 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2980 ** be released.
2981 */
drh308c2a52010-05-14 11:30:18 +00002982 if( eFileLock==SHARED_LOCK
2983 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002984 ){
2985 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002986 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002987 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002988 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002989 goto afp_end_lock;
2990 }
2991 }
2992
2993 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002994 ** operating system calls for the specified lock.
2995 */
drh308c2a52010-05-14 11:30:18 +00002996 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002997 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002998 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002999
drh8af6c222010-05-14 12:43:01 +00003000 assert( pInode->nShared==0 );
3001 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00003002
3003 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00003004 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00003005 /* note that the quality of the randomness doesn't matter that much */
3006 lk = random();
drh8af6c222010-05-14 12:43:01 +00003007 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00003008 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003009 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00003010 if( IS_LOCK_ERROR(lrc1) ){
3011 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00003012 }
aswift5b1a2562008-08-22 00:22:35 +00003013 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00003014 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00003015
aswift5b1a2562008-08-22 00:22:35 +00003016 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00003017 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00003018 rc = lrc1;
3019 goto afp_end_lock;
3020 } else if( IS_LOCK_ERROR(lrc2) ){
3021 rc = lrc2;
3022 goto afp_end_lock;
3023 } else if( lrc1 != SQLITE_OK ) {
3024 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00003025 } else {
drh308c2a52010-05-14 11:30:18 +00003026 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00003027 pInode->nLock++;
3028 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00003029 }
drh8af6c222010-05-14 12:43:01 +00003030 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00003031 /* We are trying for an exclusive lock but another thread in this
3032 ** same process is still holding a shared lock. */
3033 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00003034 }else{
3035 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3036 ** assumed that there is a SHARED or greater lock on the file
3037 ** already.
3038 */
3039 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00003040 assert( 0!=pFile->eFileLock );
3041 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003042 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00003043 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00003044 if( !failed ){
3045 context->reserved = 1;
3046 }
drhbfe66312006-10-03 17:40:40 +00003047 }
drh308c2a52010-05-14 11:30:18 +00003048 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003049 /* Acquire an EXCLUSIVE lock */
3050
3051 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00003052 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00003053 */
drh6b9d6dd2008-12-03 19:34:47 +00003054 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00003055 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00003056 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00003057 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00003058 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00003059 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00003060 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003061 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00003062 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3063 ** a critical I/O error
3064 */
drh2e233812017-08-22 15:21:54 +00003065 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00003066 SQLITE_IOERR_LOCK;
3067 goto afp_end_lock;
3068 }
3069 }else{
aswift5b1a2562008-08-22 00:22:35 +00003070 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003071 }
3072 }
aswift5b1a2562008-08-22 00:22:35 +00003073 if( failed ){
3074 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003075 }
3076 }
3077
3078 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00003079 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00003080 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00003081 }else if( eFileLock==EXCLUSIVE_LOCK ){
3082 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00003083 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00003084 }
3085
3086afp_end_lock:
drhda6dc242018-07-23 21:10:37 +00003087 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00003088 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3089 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00003090 return rc;
3091}
3092
3093/*
drh308c2a52010-05-14 11:30:18 +00003094** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00003095** must be either NO_LOCK or SHARED_LOCK.
3096**
3097** If the locking level of the file descriptor is already at or below
3098** the requested locking level, this routine is a no-op.
3099*/
drh308c2a52010-05-14 11:30:18 +00003100static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00003101 int rc = SQLITE_OK;
3102 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00003103 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00003104 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3105 int skipShared = 0;
3106#ifdef SQLITE_TEST
3107 int h = pFile->h;
3108#endif
drhbfe66312006-10-03 17:40:40 +00003109
3110 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003111 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00003112 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00003113 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00003114
drh308c2a52010-05-14 11:30:18 +00003115 assert( eFileLock<=SHARED_LOCK );
3116 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00003117 return SQLITE_OK;
3118 }
drh8af6c222010-05-14 12:43:01 +00003119 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00003120 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00003121 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00003122 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00003123 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00003124 SimulateIOErrorBenign(1);
3125 SimulateIOError( h=(-1) )
3126 SimulateIOErrorBenign(0);
3127
drhd3d8c042012-05-29 17:02:40 +00003128#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003129 /* When reducing a lock such that other processes can start
3130 ** reading the database file again, make sure that the
3131 ** transaction counter was updated if any part of the database
3132 ** file changed. If the transaction counter is not updated,
3133 ** other connections to the same file might not realize that
3134 ** the file has changed and hence might not know to flush their
3135 ** cache. The use of a stale cache can lead to database corruption.
3136 */
3137 assert( pFile->inNormalWrite==0
3138 || pFile->dbUpdate==0
3139 || pFile->transCntrChng==1 );
3140 pFile->inNormalWrite = 0;
3141#endif
aswiftaebf4132008-11-21 00:10:35 +00003142
drh308c2a52010-05-14 11:30:18 +00003143 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003144 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003145 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003146 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003147 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003148 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3149 } else {
3150 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003151 }
3152 }
drh308c2a52010-05-14 11:30:18 +00003153 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003154 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003155 }
drh308c2a52010-05-14 11:30:18 +00003156 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003157 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3158 if( !rc ){
3159 context->reserved = 0;
3160 }
aswiftaebf4132008-11-21 00:10:35 +00003161 }
drh8af6c222010-05-14 12:43:01 +00003162 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3163 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003164 }
aswiftaebf4132008-11-21 00:10:35 +00003165 }
drh308c2a52010-05-14 11:30:18 +00003166 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003167
drh7ed97b92010-01-20 13:07:21 +00003168 /* Decrement the shared lock counter. Release the lock using an
3169 ** OS call only when all threads in this same process have released
3170 ** the lock.
3171 */
drh8af6c222010-05-14 12:43:01 +00003172 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3173 pInode->nShared--;
3174 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003175 SimulateIOErrorBenign(1);
3176 SimulateIOError( h=(-1) )
3177 SimulateIOErrorBenign(0);
3178 if( !skipShared ){
3179 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3180 }
3181 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003182 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003183 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003184 }
3185 }
3186 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003187 pInode->nLock--;
3188 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00003189 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003190 }
drhbfe66312006-10-03 17:40:40 +00003191 }
drh7ed97b92010-01-20 13:07:21 +00003192
drhda6dc242018-07-23 21:10:37 +00003193 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00003194 if( rc==SQLITE_OK ){
3195 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00003196 }
drhbfe66312006-10-03 17:40:40 +00003197 return rc;
3198}
3199
3200/*
drh339eb0b2008-03-07 15:34:11 +00003201** Close a file & cleanup AFP specific locking context
3202*/
danielk1977e339d652008-06-28 11:23:00 +00003203static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003204 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003205 unixFile *pFile = (unixFile*)id;
3206 assert( id!=0 );
3207 afpUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00003208 assert( unixFileMutexNotheld(pFile) );
drha8de1e12015-11-30 00:05:39 +00003209 unixEnterMutex();
drhef52b362018-08-13 22:50:34 +00003210 if( pFile->pInode ){
3211 unixInodeInfo *pInode = pFile->pInode;
3212 sqlite3_mutex_enter(pInode->pLockMutex);
drhcb4e4b02018-09-06 19:36:29 +00003213 if( pInode->nLock ){
drhef52b362018-08-13 22:50:34 +00003214 /* If there are outstanding locks, do not actually close the file just
3215 ** yet because that would clear those locks. Instead, add the file
3216 ** descriptor to pInode->aPending. It will be automatically closed when
3217 ** the last lock is cleared.
3218 */
3219 setPendingFd(pFile);
3220 }
3221 sqlite3_mutex_leave(pInode->pLockMutex);
danielk1977e339d652008-06-28 11:23:00 +00003222 }
drha8de1e12015-11-30 00:05:39 +00003223 releaseInodeInfo(pFile);
3224 sqlite3_free(pFile->lockingContext);
3225 rc = closeUnixFile(id);
3226 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003227 return rc;
drhbfe66312006-10-03 17:40:40 +00003228}
3229
drhd2cb50b2009-01-09 21:41:17 +00003230#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003231/*
3232** The code above is the AFP lock implementation. The code is specific
3233** to MacOSX and does not work on other unix platforms. No alternative
3234** is available. If you don't compile for a mac, then the "unix-afp"
3235** VFS is not available.
3236**
3237********************* End of the AFP lock implementation **********************
3238******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003239
drh7ed97b92010-01-20 13:07:21 +00003240/******************************************************************************
3241*************************** Begin NFS Locking ********************************/
3242
3243#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3244/*
drh308c2a52010-05-14 11:30:18 +00003245 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003246 ** must be either NO_LOCK or SHARED_LOCK.
3247 **
3248 ** If the locking level of the file descriptor is already at or below
3249 ** the requested locking level, this routine is a no-op.
3250 */
drh308c2a52010-05-14 11:30:18 +00003251static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003252 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003253}
3254
3255#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3256/*
3257** The code above is the NFS lock implementation. The code is specific
3258** to MacOSX and does not work on other unix platforms. No alternative
3259** is available.
3260**
3261********************* End of the NFS lock implementation **********************
3262******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003263
3264/******************************************************************************
3265**************** Non-locking sqlite3_file methods *****************************
3266**
3267** The next division contains implementations for all methods of the
3268** sqlite3_file object other than the locking methods. The locking
3269** methods were defined in divisions above (one locking method per
3270** division). Those methods that are common to all locking modes
3271** are gather together into this division.
3272*/
drhbfe66312006-10-03 17:40:40 +00003273
3274/*
drh734c9862008-11-28 15:37:20 +00003275** Seek to the offset passed as the second argument, then read cnt
3276** bytes into pBuf. Return the number of bytes actually read.
3277**
3278** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3279** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3280** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003281** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003282** See tickets #2741 and #2681.
3283**
3284** To avoid stomping the errno value on a failed read the lastErrno value
3285** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003286*/
drh734c9862008-11-28 15:37:20 +00003287static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3288 int got;
drh58024642011-11-07 18:16:00 +00003289 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003290#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3291 i64 newOffset;
3292#endif
drh734c9862008-11-28 15:37:20 +00003293 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003294 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003295 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003296 do{
drh734c9862008-11-28 15:37:20 +00003297#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003298 got = osPread(id->h, pBuf, cnt, offset);
3299 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003300#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003301 got = osPread64(id->h, pBuf, cnt, offset);
3302 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003303#else
drha46cadc2016-03-04 03:02:06 +00003304 newOffset = lseek(id->h, offset, SEEK_SET);
3305 SimulateIOError( newOffset = -1 );
3306 if( newOffset<0 ){
3307 storeLastErrno((unixFile*)id, errno);
3308 return -1;
3309 }
3310 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003311#endif
drh58024642011-11-07 18:16:00 +00003312 if( got==cnt ) break;
3313 if( got<0 ){
3314 if( errno==EINTR ){ got = 1; continue; }
3315 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003316 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003317 break;
3318 }else if( got>0 ){
3319 cnt -= got;
3320 offset += got;
3321 prior += got;
3322 pBuf = (void*)(got + (char*)pBuf);
3323 }
3324 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003325 TIMER_END;
drh58024642011-11-07 18:16:00 +00003326 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3327 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3328 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003329}
3330
3331/*
drh734c9862008-11-28 15:37:20 +00003332** Read data from a file into a buffer. Return SQLITE_OK if all
3333** bytes were read successfully and SQLITE_IOERR if anything goes
3334** wrong.
drh339eb0b2008-03-07 15:34:11 +00003335*/
drh734c9862008-11-28 15:37:20 +00003336static int unixRead(
3337 sqlite3_file *id,
3338 void *pBuf,
3339 int amt,
3340 sqlite3_int64 offset
3341){
dan08da86a2009-08-21 17:18:03 +00003342 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003343 int got;
3344 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003345 assert( offset>=0 );
3346 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003347
drh067b92b2020-06-19 15:24:12 +00003348 /* If this is a database file (not a journal, super-journal or temp
dan08da86a2009-08-21 17:18:03 +00003349 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003350#if 0
drhc68886b2017-08-18 16:09:52 +00003351 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003352 || offset>=PENDING_BYTE+512
3353 || offset+amt<=PENDING_BYTE
3354 );
dan7c246102010-04-12 19:00:29 +00003355#endif
drh08c6d442009-02-09 17:34:07 +00003356
drh9b4c59f2013-04-15 17:03:42 +00003357#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003358 /* Deal with as much of this read request as possible by transfering
3359 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003360 if( offset<pFile->mmapSize ){
3361 if( offset+amt <= pFile->mmapSize ){
3362 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3363 return SQLITE_OK;
3364 }else{
3365 int nCopy = pFile->mmapSize - offset;
3366 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3367 pBuf = &((u8 *)pBuf)[nCopy];
3368 amt -= nCopy;
3369 offset += nCopy;
3370 }
3371 }
drh6e0b6d52013-04-09 16:19:20 +00003372#endif
danf23da962013-03-23 21:00:41 +00003373
dan08da86a2009-08-21 17:18:03 +00003374 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003375 if( got==amt ){
3376 return SQLITE_OK;
3377 }else if( got<0 ){
drh5a07d102020-11-18 12:48:48 +00003378 /* pFile->lastErrno has been set by seekAndRead().
3379 ** Usually we return SQLITE_IOERR_READ here, though for some
3380 ** kinds of errors we return SQLITE_IOERR_CORRUPTFS. The
3381 ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT
3382 ** prior to returning to the application by the sqlite3ApiExit()
3383 ** routine.
3384 */
3385 switch( pFile->lastErrno ){
3386 case ERANGE:
drh5a07d102020-11-18 12:48:48 +00003387 case EIO:
3388#ifdef ENXIO
3389 case ENXIO:
3390#endif
3391#ifdef EDEVERR
3392 case EDEVERR:
3393#endif
3394 return SQLITE_IOERR_CORRUPTFS;
3395 }
drh734c9862008-11-28 15:37:20 +00003396 return SQLITE_IOERR_READ;
3397 }else{
drh4bf66fd2015-02-19 02:43:02 +00003398 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003399 /* Unread parts of the buffer must be zero-filled */
3400 memset(&((char*)pBuf)[got], 0, amt-got);
3401 return SQLITE_IOERR_SHORT_READ;
3402 }
3403}
3404
3405/*
dan47a2b4a2013-04-26 16:09:29 +00003406** Attempt to seek the file-descriptor passed as the first argument to
3407** absolute offset iOff, then attempt to write nBuf bytes of data from
3408** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3409** return the actual number of bytes written (which may be less than
3410** nBuf).
3411*/
3412static int seekAndWriteFd(
3413 int fd, /* File descriptor to write to */
3414 i64 iOff, /* File offset to begin writing at */
3415 const void *pBuf, /* Copy data from this buffer to the file */
3416 int nBuf, /* Size of buffer pBuf in bytes */
3417 int *piErrno /* OUT: Error number if error occurs */
3418){
3419 int rc = 0; /* Value returned by system call */
3420
3421 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003422 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003423 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003424 nBuf &= 0x1ffff;
3425 TIMER_START;
3426
3427#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003428 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003429#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003430 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003431#else
3432 do{
3433 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003434 SimulateIOError( iSeek = -1 );
3435 if( iSeek<0 ){
3436 rc = -1;
3437 break;
dan47a2b4a2013-04-26 16:09:29 +00003438 }
3439 rc = osWrite(fd, pBuf, nBuf);
3440 }while( rc<0 && errno==EINTR );
3441#endif
3442
3443 TIMER_END;
3444 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3445
drhe1818ec2015-12-01 16:21:35 +00003446 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003447 return rc;
3448}
3449
3450
3451/*
drh734c9862008-11-28 15:37:20 +00003452** Seek to the offset in id->offset then read cnt bytes into pBuf.
3453** Return the number of bytes actually read. Update the offset.
3454**
3455** To avoid stomping the errno value on a failed write the lastErrno value
3456** is set before returning.
3457*/
3458static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003459 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003460}
3461
3462
3463/*
3464** Write data from a buffer into a file. Return SQLITE_OK on success
3465** or some other error code on failure.
3466*/
3467static int unixWrite(
3468 sqlite3_file *id,
3469 const void *pBuf,
3470 int amt,
3471 sqlite3_int64 offset
3472){
dan08da86a2009-08-21 17:18:03 +00003473 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003474 int wrote = 0;
3475 assert( id );
3476 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003477
drh067b92b2020-06-19 15:24:12 +00003478 /* If this is a database file (not a journal, super-journal or temp
dan08da86a2009-08-21 17:18:03 +00003479 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003480#if 0
drhc68886b2017-08-18 16:09:52 +00003481 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003482 || offset>=PENDING_BYTE+512
3483 || offset+amt<=PENDING_BYTE
3484 );
dan7c246102010-04-12 19:00:29 +00003485#endif
drh08c6d442009-02-09 17:34:07 +00003486
drhd3d8c042012-05-29 17:02:40 +00003487#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003488 /* If we are doing a normal write to a database file (as opposed to
3489 ** doing a hot-journal rollback or a write to some file other than a
3490 ** normal database file) then record the fact that the database
3491 ** has changed. If the transaction counter is modified, record that
3492 ** fact too.
3493 */
dan08da86a2009-08-21 17:18:03 +00003494 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003495 pFile->dbUpdate = 1; /* The database has been modified */
3496 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003497 int rc;
drh8f941bc2009-01-14 23:03:40 +00003498 char oldCntr[4];
3499 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003500 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003501 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003502 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003503 pFile->transCntrChng = 1; /* The transaction counter has changed */
3504 }
3505 }
3506 }
3507#endif
3508
danfe33e392015-11-17 20:56:06 +00003509#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003510 /* Deal with as much of this write request as possible by transfering
3511 ** data from the memory mapping using memcpy(). */
3512 if( offset<pFile->mmapSize ){
3513 if( offset+amt <= pFile->mmapSize ){
3514 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3515 return SQLITE_OK;
3516 }else{
3517 int nCopy = pFile->mmapSize - offset;
3518 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3519 pBuf = &((u8 *)pBuf)[nCopy];
3520 amt -= nCopy;
3521 offset += nCopy;
3522 }
3523 }
drh6e0b6d52013-04-09 16:19:20 +00003524#endif
drh02bf8b42015-09-01 23:51:53 +00003525
3526 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003527 amt -= wrote;
3528 offset += wrote;
3529 pBuf = &((char*)pBuf)[wrote];
3530 }
3531 SimulateIOError(( wrote=(-1), amt=1 ));
3532 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003533
drh02bf8b42015-09-01 23:51:53 +00003534 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003535 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003536 /* lastErrno set by seekAndWrite */
3537 return SQLITE_IOERR_WRITE;
3538 }else{
drh4bf66fd2015-02-19 02:43:02 +00003539 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003540 return SQLITE_FULL;
3541 }
3542 }
dan6e09d692010-07-27 18:34:15 +00003543
drh734c9862008-11-28 15:37:20 +00003544 return SQLITE_OK;
3545}
3546
3547#ifdef SQLITE_TEST
3548/*
3549** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003550** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003551*/
3552int sqlite3_sync_count = 0;
3553int sqlite3_fullsync_count = 0;
3554#endif
3555
3556/*
drh89240432009-03-25 01:06:01 +00003557** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003558** Others do no. To be safe, we will stick with the (slightly slower)
3559** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003560** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003561*/
drhf7a4a1b2015-01-10 18:02:45 +00003562#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003563# define fdatasync fsync
3564#endif
3565
3566/*
3567** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3568** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3569** only available on Mac OS X. But that could change.
3570*/
3571#ifdef F_FULLFSYNC
3572# define HAVE_FULLFSYNC 1
3573#else
3574# define HAVE_FULLFSYNC 0
3575#endif
3576
3577
3578/*
3579** The fsync() system call does not work as advertised on many
3580** unix systems. The following procedure is an attempt to make
3581** it work better.
3582**
3583** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3584** for testing when we want to run through the test suite quickly.
3585** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3586** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3587** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003588**
3589** SQLite sets the dataOnly flag if the size of the file is unchanged.
3590** The idea behind dataOnly is that it should only write the file content
3591** to disk, not the inode. We only set dataOnly if the file size is
3592** unchanged since the file size is part of the inode. However,
3593** Ted Ts'o tells us that fdatasync() will also write the inode if the
3594** file size has changed. The only real difference between fdatasync()
3595** and fsync(), Ted tells us, is that fdatasync() will not flush the
3596** inode if the mtime or owner or other inode attributes have changed.
3597** We only care about the file size, not the other file attributes, so
3598** as far as SQLite is concerned, an fdatasync() is always adequate.
3599** So, we always use fdatasync() if it is available, regardless of
3600** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003601*/
3602static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003603 int rc;
drh734c9862008-11-28 15:37:20 +00003604
3605 /* The following "ifdef/elif/else/" block has the same structure as
3606 ** the one below. It is replicated here solely to avoid cluttering
3607 ** up the real code with the UNUSED_PARAMETER() macros.
3608 */
3609#ifdef SQLITE_NO_SYNC
3610 UNUSED_PARAMETER(fd);
3611 UNUSED_PARAMETER(fullSync);
3612 UNUSED_PARAMETER(dataOnly);
3613#elif HAVE_FULLFSYNC
3614 UNUSED_PARAMETER(dataOnly);
3615#else
3616 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003617 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003618#endif
3619
3620 /* Record the number of times that we do a normal fsync() and
3621 ** FULLSYNC. This is used during testing to verify that this procedure
3622 ** gets called with the correct arguments.
3623 */
3624#ifdef SQLITE_TEST
3625 if( fullSync ) sqlite3_fullsync_count++;
3626 sqlite3_sync_count++;
3627#endif
3628
3629 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003630 ** no-op. But go ahead and call fstat() to validate the file
3631 ** descriptor as we need a method to provoke a failure during
3632 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003633 */
3634#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003635 {
3636 struct stat buf;
3637 rc = osFstat(fd, &buf);
3638 }
drh734c9862008-11-28 15:37:20 +00003639#elif HAVE_FULLFSYNC
3640 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003641 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003642 }else{
3643 rc = 1;
3644 }
3645 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003646 ** It shouldn't be possible for fullfsync to fail on the local
3647 ** file system (on OSX), so failure indicates that FULLFSYNC
3648 ** isn't supported for this file system. So, attempt an fsync
3649 ** and (for now) ignore the overhead of a superfluous fcntl call.
3650 ** It'd be better to detect fullfsync support once and avoid
3651 ** the fcntl call every time sync is called.
3652 */
drh734c9862008-11-28 15:37:20 +00003653 if( rc ) rc = fsync(fd);
3654
drh7ed97b92010-01-20 13:07:21 +00003655#elif defined(__APPLE__)
3656 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3657 ** so currently we default to the macro that redefines fdatasync to fsync
3658 */
3659 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003660#else
drh0b647ff2009-03-21 14:41:04 +00003661 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003662#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003663 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003664 rc = fsync(fd);
3665 }
drh0b647ff2009-03-21 14:41:04 +00003666#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003667#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3668
3669 if( OS_VXWORKS && rc!= -1 ){
3670 rc = 0;
3671 }
chw97185482008-11-17 08:05:31 +00003672 return rc;
drhbfe66312006-10-03 17:40:40 +00003673}
3674
drh734c9862008-11-28 15:37:20 +00003675/*
drh0059eae2011-08-08 23:48:40 +00003676** Open a file descriptor to the directory containing file zFilename.
3677** If successful, *pFd is set to the opened file descriptor and
3678** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3679** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3680** value.
3681**
drh90315a22011-08-10 01:52:12 +00003682** The directory file descriptor is used for only one thing - to
3683** fsync() a directory to make sure file creation and deletion events
3684** are flushed to disk. Such fsyncs are not needed on newer
3685** journaling filesystems, but are required on older filesystems.
3686**
3687** This routine can be overridden using the xSetSysCall interface.
3688** The ability to override this routine was added in support of the
3689** chromium sandbox. Opening a directory is a security risk (we are
3690** told) so making it overrideable allows the chromium sandbox to
3691** replace this routine with a harmless no-op. To make this routine
3692** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3693** *pFd set to a negative number.
3694**
drh0059eae2011-08-08 23:48:40 +00003695** If SQLITE_OK is returned, the caller is responsible for closing
3696** the file descriptor *pFd using close().
3697*/
3698static int openDirectory(const char *zFilename, int *pFd){
3699 int ii;
3700 int fd = -1;
3701 char zDirname[MAX_PATHNAME+1];
3702
3703 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003704 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3705 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003706 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003707 }else{
3708 if( zDirname[0]!='/' ) zDirname[0] = '.';
3709 zDirname[1] = 0;
3710 }
drh3b9f1542020-04-20 17:35:32 +00003711 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drhdc278512015-12-07 18:18:33 +00003712 if( fd>=0 ){
3713 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003714 }
3715 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003716 if( fd>=0 ) return SQLITE_OK;
3717 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003718}
3719
3720/*
drh734c9862008-11-28 15:37:20 +00003721** Make sure all writes to a particular file are committed to disk.
3722**
3723** If dataOnly==0 then both the file itself and its metadata (file
3724** size, access time, etc) are synced. If dataOnly!=0 then only the
3725** file data is synced.
3726**
3727** Under Unix, also make sure that the directory entry for the file
3728** has been created by fsync-ing the directory that contains the file.
3729** If we do not do this and we encounter a power failure, the directory
3730** entry for the journal might not exist after we reboot. The next
3731** SQLite to access the file will not know that the journal exists (because
3732** the directory entry for the journal was never created) and the transaction
3733** will not roll back - possibly leading to database corruption.
3734*/
3735static int unixSync(sqlite3_file *id, int flags){
3736 int rc;
3737 unixFile *pFile = (unixFile*)id;
3738
3739 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3740 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3741
3742 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3743 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3744 || (flags&0x0F)==SQLITE_SYNC_FULL
3745 );
3746
3747 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3748 ** line is to test that doing so does not cause any problems.
3749 */
3750 SimulateDiskfullError( return SQLITE_FULL );
3751
3752 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003753 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003754 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3755 SimulateIOError( rc=1 );
3756 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003757 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003758 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003759 }
drh0059eae2011-08-08 23:48:40 +00003760
3761 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003762 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003763 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003764 */
3765 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3766 int dirfd;
3767 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003768 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003769 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003770 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003771 full_fsync(dirfd, 0, 0);
3772 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003773 }else{
3774 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003775 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003776 }
drh0059eae2011-08-08 23:48:40 +00003777 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003778 }
3779 return rc;
3780}
3781
3782/*
3783** Truncate an open file to a specified size
3784*/
3785static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003786 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003787 int rc;
dan6e09d692010-07-27 18:34:15 +00003788 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003789 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003790
3791 /* If the user has configured a chunk-size for this file, truncate the
3792 ** file so that it consists of an integer number of chunks (i.e. the
3793 ** actual file size after the operation may be larger than the requested
3794 ** size).
3795 */
drhb8af4b72012-04-05 20:04:39 +00003796 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003797 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3798 }
3799
dan2ee53412014-09-06 16:49:40 +00003800 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003801 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003802 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003803 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003804 }else{
drhd3d8c042012-05-29 17:02:40 +00003805#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003806 /* If we are doing a normal write to a database file (as opposed to
3807 ** doing a hot-journal rollback or a write to some file other than a
3808 ** normal database file) and we truncate the file to zero length,
3809 ** that effectively updates the change counter. This might happen
3810 ** when restoring a database using the backup API from a zero-length
3811 ** source.
3812 */
dan6e09d692010-07-27 18:34:15 +00003813 if( pFile->inNormalWrite && nByte==0 ){
3814 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003815 }
danf23da962013-03-23 21:00:41 +00003816#endif
danc0003312013-03-22 17:46:11 +00003817
mistachkine98844f2013-08-24 00:59:24 +00003818#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003819 /* If the file was just truncated to a size smaller than the currently
3820 ** mapped region, reduce the effective mapping size as well. SQLite will
3821 ** use read() and write() to access data beyond this point from now on.
3822 */
3823 if( nByte<pFile->mmapSize ){
3824 pFile->mmapSize = nByte;
3825 }
mistachkine98844f2013-08-24 00:59:24 +00003826#endif
drh3313b142009-11-06 04:13:18 +00003827
drh734c9862008-11-28 15:37:20 +00003828 return SQLITE_OK;
3829 }
3830}
3831
3832/*
3833** Determine the current size of a file in bytes
3834*/
3835static int unixFileSize(sqlite3_file *id, i64 *pSize){
3836 int rc;
3837 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003838 assert( id );
3839 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003840 SimulateIOError( rc=1 );
3841 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003842 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003843 return SQLITE_IOERR_FSTAT;
3844 }
3845 *pSize = buf.st_size;
3846
drh8af6c222010-05-14 12:43:01 +00003847 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003848 ** writes a single byte into that file in order to work around a bug
3849 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3850 ** layers, we need to report this file size as zero even though it is
3851 ** really 1. Ticket #3260.
3852 */
3853 if( *pSize==1 ) *pSize = 0;
3854
3855
3856 return SQLITE_OK;
3857}
3858
drhd2cb50b2009-01-09 21:41:17 +00003859#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003860/*
3861** Handler for proxy-locking file-control verbs. Defined below in the
3862** proxying locking division.
3863*/
3864static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003865#endif
drh715ff302008-12-03 22:32:44 +00003866
dan502019c2010-07-28 14:26:17 +00003867/*
3868** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003869** file-control operation. Enlarge the database to nBytes in size
3870** (rounded up to the next chunk-size). If the database is already
3871** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003872*/
3873static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003874 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003875 i64 nSize; /* Required file size */
3876 struct stat buf; /* Used to hold return values of fstat() */
3877
drh4bf66fd2015-02-19 02:43:02 +00003878 if( osFstat(pFile->h, &buf) ){
3879 return SQLITE_IOERR_FSTAT;
3880 }
dan502019c2010-07-28 14:26:17 +00003881
3882 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3883 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003884
dan502019c2010-07-28 14:26:17 +00003885#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003886 /* The code below is handling the return value of osFallocate()
3887 ** correctly. posix_fallocate() is defined to "returns zero on success,
3888 ** or an error number on failure". See the manpage for details. */
3889 int err;
drhff812312011-02-23 13:33:46 +00003890 do{
dan661d71a2011-03-30 19:08:03 +00003891 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3892 }while( err==EINTR );
drh789df142018-06-02 14:37:39 +00003893 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003894#else
dan592bf7f2014-12-30 19:58:31 +00003895 /* If the OS does not have posix_fallocate(), fake it. Write a
3896 ** single byte to the last byte in each block that falls entirely
3897 ** within the extended region. Then, if required, a single byte
3898 ** at offset (nSize-1), to set the size of the file correctly.
3899 ** This is a similar technique to that used by glibc on systems
3900 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003901 */
3902 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003903 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003904 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003905
drh053378d2015-12-01 22:09:42 +00003906 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003907 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003908 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003909 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3910 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003911 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003912 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003913 }
dan502019c2010-07-28 14:26:17 +00003914#endif
3915 }
3916 }
3917
mistachkine98844f2013-08-24 00:59:24 +00003918#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003919 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003920 int rc;
3921 if( pFile->szChunk<=0 ){
3922 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003923 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003924 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3925 }
3926 }
3927
3928 rc = unixMapfile(pFile, nByte);
3929 return rc;
3930 }
mistachkine98844f2013-08-24 00:59:24 +00003931#endif
danf23da962013-03-23 21:00:41 +00003932
dan502019c2010-07-28 14:26:17 +00003933 return SQLITE_OK;
3934}
danielk1977ad94b582007-08-20 06:44:22 +00003935
danielk1977e3026632004-06-22 11:29:02 +00003936/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003937** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003938** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3939**
3940** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3941*/
3942static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3943 if( *pArg<0 ){
3944 *pArg = (pFile->ctrlFlags & mask)!=0;
3945 }else if( (*pArg)==0 ){
3946 pFile->ctrlFlags &= ~mask;
3947 }else{
3948 pFile->ctrlFlags |= mask;
3949 }
3950}
3951
drh696b33e2012-12-06 19:01:42 +00003952/* Forward declaration */
3953static int unixGetTempname(int nBuf, char *zBuf);
danaecc04d2021-04-02 19:55:48 +00003954static int unixFcntlExternalReader(unixFile*, int*);
drh696b33e2012-12-06 19:01:42 +00003955
drhf12b3f62011-12-21 14:42:29 +00003956/*
drh9e33c2c2007-08-31 18:34:59 +00003957** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003958*/
drhcc6bb3e2007-08-31 16:11:35 +00003959static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003960 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003961 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003962#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003963 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3964 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003965 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003966 }
3967 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3968 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003969 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003970 }
3971 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3972 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003973 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003974 }
drhd76dba72017-07-22 16:00:34 +00003975#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003976
drh9e33c2c2007-08-31 18:34:59 +00003977 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003978 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003979 return SQLITE_OK;
3980 }
drh4bf66fd2015-02-19 02:43:02 +00003981 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003982 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003983 return SQLITE_OK;
3984 }
dan6e09d692010-07-27 18:34:15 +00003985 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003986 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003987 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003988 }
drh9ff27ec2010-05-19 19:26:05 +00003989 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003990 int rc;
3991 SimulateIOErrorBenign(1);
3992 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3993 SimulateIOErrorBenign(0);
3994 return rc;
drhf0b190d2011-07-26 16:03:07 +00003995 }
3996 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003997 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3998 return SQLITE_OK;
3999 }
drhcb15f352011-12-23 01:04:17 +00004000 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
4001 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00004002 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00004003 }
drhde60fc22011-12-14 17:53:36 +00004004 case SQLITE_FCNTL_VFSNAME: {
4005 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
4006 return SQLITE_OK;
4007 }
drh696b33e2012-12-06 19:01:42 +00004008 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00004009 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00004010 if( zTFile ){
4011 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
4012 *(char**)pArg = zTFile;
4013 }
4014 return SQLITE_OK;
4015 }
drhb959a012013-12-07 12:29:22 +00004016 case SQLITE_FCNTL_HAS_MOVED: {
4017 *(int*)pArg = fileHasMoved(pFile);
4018 return SQLITE_OK;
4019 }
drhf0119b22018-03-26 17:40:53 +00004020#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4021 case SQLITE_FCNTL_LOCK_TIMEOUT: {
dan97ccc1b2020-03-27 17:23:17 +00004022 int iOld = pFile->iBusyTimeout;
drhf0119b22018-03-26 17:40:53 +00004023 pFile->iBusyTimeout = *(int*)pArg;
dan97ccc1b2020-03-27 17:23:17 +00004024 *(int*)pArg = iOld;
drhf0119b22018-03-26 17:40:53 +00004025 return SQLITE_OK;
4026 }
4027#endif
mistachkine98844f2013-08-24 00:59:24 +00004028#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00004029 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00004030 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00004031 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00004032 if( newLimit>sqlite3GlobalConfig.mxMmap ){
4033 newLimit = sqlite3GlobalConfig.mxMmap;
4034 }
dan43c1e622017-08-07 18:13:28 +00004035
4036 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00004037 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4038 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00004039 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00004040 newLimit = (newLimit & 0x7FFFFFFF);
4041 }
4042
drh9b4c59f2013-04-15 17:03:42 +00004043 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00004044 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00004045 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00004046 if( pFile->mmapSize>0 ){
4047 unixUnmapfile(pFile);
4048 rc = unixMapfile(pFile, -1);
4049 }
danbcb8a862013-04-08 15:30:41 +00004050 }
drh34e258c2013-05-23 01:40:53 +00004051 return rc;
danb2d3de32013-03-14 18:34:37 +00004052 }
mistachkine98844f2013-08-24 00:59:24 +00004053#endif
drhd3d8c042012-05-29 17:02:40 +00004054#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00004055 /* The pager calls this method to signal that it has done
4056 ** a rollback and that the database is therefore unchanged and
4057 ** it hence it is OK for the transaction change counter to be
4058 ** unchanged.
4059 */
4060 case SQLITE_FCNTL_DB_UNCHANGED: {
4061 ((unixFile*)id)->dbUpdate = 0;
4062 return SQLITE_OK;
4063 }
4064#endif
drhd2cb50b2009-01-09 21:41:17 +00004065#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00004066 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4067 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00004068 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00004069 }
drhd2cb50b2009-01-09 21:41:17 +00004070#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
danaecc04d2021-04-02 19:55:48 +00004071
4072 case SQLITE_FCNTL_EXTERNAL_READER: {
4073 return unixFcntlExternalReader((unixFile*)id, (int*)pArg);
4074 }
drh9e33c2c2007-08-31 18:34:59 +00004075 }
drh0b52b7d2011-01-26 19:46:22 +00004076 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00004077}
4078
4079/*
danefe16972017-07-20 19:49:14 +00004080** If pFd->sectorSize is non-zero when this function is called, it is a
4081** no-op. Otherwise, the values of pFd->sectorSize and
4082** pFd->deviceCharacteristics are set according to the file-system
4083** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00004084**
danefe16972017-07-20 19:49:14 +00004085** There are two versions of this function. One for QNX and one for all
4086** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00004087*/
danefe16972017-07-20 19:49:14 +00004088#ifndef __QNXNTO__
4089static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00004090 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00004091 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00004092#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00004093 int res;
dan9d709542017-07-21 21:06:24 +00004094 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00004095
danefe16972017-07-20 19:49:14 +00004096 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00004097 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4098 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00004099 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00004100 }
drhd76dba72017-07-22 16:00:34 +00004101#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00004102
4103 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4104 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4105 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4106 }
4107
4108 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4109 }
4110}
4111#else
drh537dddf2012-10-26 13:46:24 +00004112#include <sys/dcmd_blk.h>
4113#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00004114static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00004115 if( pFile->sectorSize == 0 ){
4116 struct statvfs fsInfo;
4117
4118 /* Set defaults for non-supported filesystems */
4119 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4120 pFile->deviceCharacteristics = 0;
4121 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00004122 return;
drh537dddf2012-10-26 13:46:24 +00004123 }
4124
4125 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4126 pFile->sectorSize = fsInfo.f_bsize;
4127 pFile->deviceCharacteristics =
4128 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4129 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4130 ** the write succeeds */
4131 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4132 ** so it is ordered */
4133 0;
4134 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4135 pFile->sectorSize = fsInfo.f_bsize;
4136 pFile->deviceCharacteristics =
4137 /* etfs cluster size writes are atomic */
4138 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4139 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4140 ** the write succeeds */
4141 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4142 ** so it is ordered */
4143 0;
4144 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4145 pFile->sectorSize = fsInfo.f_bsize;
4146 pFile->deviceCharacteristics =
4147 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4148 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4149 ** the write succeeds */
4150 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4151 ** so it is ordered */
4152 0;
4153 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4154 pFile->sectorSize = fsInfo.f_bsize;
4155 pFile->deviceCharacteristics =
4156 /* full bitset of atomics from max sector size and smaller */
4157 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4158 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4159 ** so it is ordered */
4160 0;
4161 }else if( strstr(fsInfo.f_basetype, "dos") ){
4162 pFile->sectorSize = fsInfo.f_bsize;
4163 pFile->deviceCharacteristics =
4164 /* full bitset of atomics from max sector size and smaller */
4165 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4166 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4167 ** so it is ordered */
4168 0;
4169 }else{
4170 pFile->deviceCharacteristics =
4171 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4172 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4173 ** the write succeeds */
4174 0;
4175 }
4176 }
4177 /* Last chance verification. If the sector size isn't a multiple of 512
4178 ** then it isn't valid.*/
4179 if( pFile->sectorSize % 512 != 0 ){
4180 pFile->deviceCharacteristics = 0;
4181 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4182 }
drh537dddf2012-10-26 13:46:24 +00004183}
danefe16972017-07-20 19:49:14 +00004184#endif
4185
4186/*
4187** Return the sector size in bytes of the underlying block device for
4188** the specified file. This is almost always 512 bytes, but may be
4189** larger for some devices.
4190**
4191** SQLite code assumes this function cannot fail. It also assumes that
4192** if two files are created in the same file-system directory (i.e.
4193** a database and its journal file) that the sector size will be the
4194** same for both.
4195*/
4196static int unixSectorSize(sqlite3_file *id){
4197 unixFile *pFd = (unixFile*)id;
4198 setDeviceCharacteristics(pFd);
4199 return pFd->sectorSize;
4200}
danielk1977a3d4c882007-03-23 10:08:38 +00004201
danielk197790949c22007-08-17 16:50:38 +00004202/*
drhf12b3f62011-12-21 14:42:29 +00004203** Return the device characteristics for the file.
4204**
drhcb15f352011-12-23 01:04:17 +00004205** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004206** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004207** file system does not always provide powersafe overwrites. (In other
4208** words, after a power-loss event, parts of the file that were never
4209** written might end up being altered.) However, non-PSOW behavior is very,
4210** very rare. And asserting PSOW makes a large reduction in the amount
4211** of required I/O for journaling, since a lot of padding is eliminated.
4212** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4213** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004214*/
drhf12b3f62011-12-21 14:42:29 +00004215static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004216 unixFile *pFd = (unixFile*)id;
4217 setDeviceCharacteristics(pFd);
4218 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004219}
4220
dan702eec12014-06-23 10:04:58 +00004221#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004222
dan702eec12014-06-23 10:04:58 +00004223/*
4224** Return the system page size.
4225**
4226** This function should not be called directly by other code in this file.
4227** Instead, it should be called via macro osGetpagesize().
4228*/
4229static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004230#if OS_VXWORKS
4231 return 1024;
4232#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004233 return getpagesize();
4234#else
4235 return (int)sysconf(_SC_PAGESIZE);
4236#endif
4237}
4238
4239#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4240
4241#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004242
4243/*
drhd91c68f2010-05-14 14:52:25 +00004244** Object used to represent an shared memory buffer.
4245**
4246** When multiple threads all reference the same wal-index, each thread
4247** has its own unixShm object, but they all point to a single instance
4248** of this unixShmNode object. In other words, each wal-index is opened
4249** only once per process.
4250**
4251** Each unixShmNode object is connected to a single unixInodeInfo object.
4252** We could coalesce this object into unixInodeInfo, but that would mean
4253** every open file that does not use shared memory (in other words, most
4254** open files) would have to carry around this extra information. So
4255** the unixInodeInfo object contains a pointer to this unixShmNode object
4256** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004257**
4258** unixMutexHeld() must be true when creating or destroying
4259** this object or while reading or writing the following fields:
4260**
4261** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004262**
4263** The following fields are read-only after the object is created:
4264**
drh8820c8d2018-10-02 19:58:08 +00004265** hShm
drhd9e5c4f2010-05-12 18:01:39 +00004266** zFilename
4267**
drh8820c8d2018-10-02 19:58:08 +00004268** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004269** unixMutexHeld() is true when reading or writing any other field
4270** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004271*/
drhd91c68f2010-05-14 14:52:25 +00004272struct unixShmNode {
4273 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drh24efa542018-10-02 19:36:40 +00004274 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004275 char *zFilename; /* Name of the mmapped file */
drh8820c8d2018-10-02 19:58:08 +00004276 int hShm; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004277 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004278 u16 nRegion; /* Size of array apRegion */
4279 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004280 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004281 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004282 int nRef; /* Number of unixShm objects pointing to this */
4283 unixShm *pFirst; /* All unixShm objects pointing to this */
dan8337da62020-08-28 19:27:15 +00004284 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
drhd9e5c4f2010-05-12 18:01:39 +00004285#ifdef SQLITE_DEBUG
4286 u8 exclMask; /* Mask of exclusive locks held */
4287 u8 sharedMask; /* Mask of shared locks held */
4288 u8 nextShmId; /* Next available unixShm.id value */
4289#endif
4290};
4291
4292/*
drhd9e5c4f2010-05-12 18:01:39 +00004293** Structure used internally by this VFS to record the state of an
4294** open shared memory connection.
4295**
drhd91c68f2010-05-14 14:52:25 +00004296** The following fields are initialized when this object is created and
4297** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004298**
drh24efa542018-10-02 19:36:40 +00004299** unixShm.pShmNode
drhd91c68f2010-05-14 14:52:25 +00004300** unixShm.id
4301**
drh24efa542018-10-02 19:36:40 +00004302** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4303** be held while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004304*/
4305struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004306 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4307 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drh24efa542018-10-02 19:36:40 +00004308 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
drhfd532312011-08-31 18:35:34 +00004309 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004310 u16 sharedMask; /* Mask of shared locks held */
4311 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004312};
4313
4314/*
drhd9e5c4f2010-05-12 18:01:39 +00004315** Constants used for locking
4316*/
drhbd9676c2010-06-23 17:58:38 +00004317#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004318#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004319
drhd9e5c4f2010-05-12 18:01:39 +00004320/*
danaecc04d2021-04-02 19:55:48 +00004321** Use F_GETLK to check whether or not there are any readers with open
4322** wal-mode transactions in other processes on database file pFile. If
4323** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are
4324** such transactions, or 0 otherwise. If an error occurs, return an
4325** SQLite error code. The final value of *piOut is undefined in this
4326** case.
4327*/
4328static int unixFcntlExternalReader(unixFile *pFile, int *piOut){
4329 int rc = SQLITE_OK;
4330 *piOut = 0;
4331 if( pFile->pShm){
4332 unixShmNode *pShmNode = pFile->pShm->pShmNode;
4333 struct flock f;
4334
4335 memset(&f, 0, sizeof(f));
4336 f.l_type = F_WRLCK;
4337 f.l_whence = SEEK_SET;
4338 f.l_start = UNIX_SHM_BASE + 3;
4339 f.l_len = SQLITE_SHM_NLOCK - 3;
4340
4341 sqlite3_mutex_enter(pShmNode->pShmMutex);
4342 if( osFcntl(pShmNode->hShm, F_GETLK, &f)<0 ){
4343 rc = SQLITE_IOERR_LOCK;
4344 }else{
4345 *piOut = (f.l_type!=F_UNLCK);
4346 }
4347 sqlite3_mutex_leave(pShmNode->pShmMutex);
4348 }
4349
4350 return rc;
4351}
4352
4353
4354/*
drh73b64e42010-05-30 19:55:15 +00004355** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004356**
4357** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4358** otherwise.
4359*/
4360static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004361 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004362 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004363 int ofst, /* First byte of the locking range */
4364 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004365){
drhbbf76ee2015-03-10 20:22:35 +00004366 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4367 struct flock f; /* The posix advisory locking structure */
4368 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004369
drhd91c68f2010-05-14 14:52:25 +00004370 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004371 pShmNode = pFile->pInode->pShmNode;
drh24efa542018-10-02 19:36:40 +00004372 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
drh9b7e8e12018-10-02 20:16:41 +00004373 assert( pShmNode->nRef>0 || unixMutexHeld() );
drhd9e5c4f2010-05-12 18:01:39 +00004374
dan9181ae92017-10-26 17:05:22 +00004375 /* Shared locks never span more than one byte */
4376 assert( n==1 || lockType!=F_RDLCK );
4377
4378 /* Locks are within range */
4379 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4380
drh8820c8d2018-10-02 19:58:08 +00004381 if( pShmNode->hShm>=0 ){
dan7bb8b8a2020-05-06 20:27:18 +00004382 int res;
drh3cb93392011-03-12 18:10:44 +00004383 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004384 f.l_type = lockType;
4385 f.l_whence = SEEK_SET;
4386 f.l_start = ofst;
4387 f.l_len = n;
dan7bb8b8a2020-05-06 20:27:18 +00004388 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
4389 if( res==-1 ){
dan7a623e12020-05-06 20:45:11 +00004390#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
dan7bb8b8a2020-05-06 20:27:18 +00004391 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
dan7a623e12020-05-06 20:45:11 +00004392#else
4393 rc = SQLITE_BUSY;
4394#endif
dan7bb8b8a2020-05-06 20:27:18 +00004395 }
drh3cb93392011-03-12 18:10:44 +00004396 }
drhd9e5c4f2010-05-12 18:01:39 +00004397
4398 /* Update the global lock state and do debug tracing */
4399#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004400 { u16 mask;
4401 OSTRACE(("SHM-LOCK "));
4402 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4403 if( rc==SQLITE_OK ){
4404 if( lockType==F_UNLCK ){
4405 OSTRACE(("unlock %d ok", ofst));
4406 pShmNode->exclMask &= ~mask;
4407 pShmNode->sharedMask &= ~mask;
4408 }else if( lockType==F_RDLCK ){
4409 OSTRACE(("read-lock %d ok", ofst));
4410 pShmNode->exclMask &= ~mask;
4411 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004412 }else{
dan9181ae92017-10-26 17:05:22 +00004413 assert( lockType==F_WRLCK );
4414 OSTRACE(("write-lock %d ok", ofst));
4415 pShmNode->exclMask |= mask;
4416 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004417 }
dan9181ae92017-10-26 17:05:22 +00004418 }else{
4419 if( lockType==F_UNLCK ){
4420 OSTRACE(("unlock %d failed", ofst));
4421 }else if( lockType==F_RDLCK ){
4422 OSTRACE(("read-lock failed"));
4423 }else{
4424 assert( lockType==F_WRLCK );
4425 OSTRACE(("write-lock %d failed", ofst));
4426 }
4427 }
4428 OSTRACE((" - afterwards %03x,%03x\n",
4429 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004430 }
drhd9e5c4f2010-05-12 18:01:39 +00004431#endif
4432
4433 return rc;
4434}
4435
dan781e34c2014-03-20 08:59:47 +00004436/*
dan781e34c2014-03-20 08:59:47 +00004437** Return the minimum number of 32KB shm regions that should be mapped at
4438** a time, assuming that each mapping must be an integer multiple of the
4439** current system page-size.
4440**
4441** Usually, this is 1. The exception seems to be systems that are configured
4442** to use 64KB pages - in this case each mapping must cover at least two
4443** shm regions.
4444*/
4445static int unixShmRegionPerMap(void){
4446 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004447 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004448 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4449 if( pgsz<shmsz ) return 1;
4450 return pgsz/shmsz;
4451}
drhd9e5c4f2010-05-12 18:01:39 +00004452
4453/*
drhd91c68f2010-05-14 14:52:25 +00004454** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004455**
4456** This is not a VFS shared-memory method; it is a utility function called
4457** by VFS shared-memory methods.
4458*/
drhd91c68f2010-05-14 14:52:25 +00004459static void unixShmPurge(unixFile *pFd){
4460 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004461 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004462 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004463 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004464 int i;
drhd91c68f2010-05-14 14:52:25 +00004465 assert( p->pInode==pFd->pInode );
drh24efa542018-10-02 19:36:40 +00004466 sqlite3_mutex_free(p->pShmMutex);
dan781e34c2014-03-20 08:59:47 +00004467 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh8820c8d2018-10-02 19:58:08 +00004468 if( p->hShm>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004469 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004470 }else{
4471 sqlite3_free(p->apRegion[i]);
4472 }
dan13a3cb82010-06-11 19:04:21 +00004473 }
dan18801912010-06-14 14:07:50 +00004474 sqlite3_free(p->apRegion);
drh8820c8d2018-10-02 19:58:08 +00004475 if( p->hShm>=0 ){
4476 robust_close(pFd, p->hShm, __LINE__);
4477 p->hShm = -1;
drh0e9365c2011-03-02 02:08:13 +00004478 }
drhd91c68f2010-05-14 14:52:25 +00004479 p->pInode->pShmNode = 0;
4480 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004481 }
4482}
4483
4484/*
dan92c02da2017-11-01 20:59:28 +00004485** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4486** take it now. Return SQLITE_OK if successful, or an SQLite error
4487** code otherwise.
4488**
4489** If the DMS cannot be locked because this is a readonly_shm=1
4490** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004491** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004492*/
4493static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4494 struct flock lock;
4495 int rc = SQLITE_OK;
4496
4497 /* Use F_GETLK to determine the locks other processes are holding
4498 ** on the DMS byte. If it indicates that another process is holding
4499 ** a SHARED lock, then this process may also take a SHARED lock
4500 ** and proceed with opening the *-shm file.
4501 **
4502 ** Or, if no other process is holding any lock, then this process
4503 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4504 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4505 ** downgrade to a SHARED lock on the DMS byte.
4506 **
4507 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4508 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4509 ** version of this code attempted the SHARED lock at this point. But
4510 ** this introduced a subtle race condition: if the process holding
4511 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4512 ** process might open and use the *-shm file without truncating it.
4513 ** And if the *-shm file has been corrupted by a power failure or
4514 ** system crash, the database itself may also become corrupt. */
4515 lock.l_whence = SEEK_SET;
4516 lock.l_start = UNIX_SHM_DMS;
4517 lock.l_len = 1;
4518 lock.l_type = F_WRLCK;
drh8820c8d2018-10-02 19:58:08 +00004519 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
dan92c02da2017-11-01 20:59:28 +00004520 rc = SQLITE_IOERR_LOCK;
4521 }else if( lock.l_type==F_UNLCK ){
4522 if( pShmNode->isReadonly ){
4523 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004524 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004525 }else{
4526 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
drhf7f2a822018-10-11 13:51:48 +00004527 /* The first connection to attach must truncate the -shm file. We
4528 ** truncate to 3 bytes (an arbitrary small number, less than the
4529 ** -shm header size) rather than 0 as a system debugging aid, to
4530 ** help detect if a -shm file truncation is legitimate or is the work
4531 ** or a rogue process. */
4532 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
dan92c02da2017-11-01 20:59:28 +00004533 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4534 }
4535 }
4536 }else if( lock.l_type==F_WRLCK ){
4537 rc = SQLITE_BUSY;
4538 }
4539
4540 if( rc==SQLITE_OK ){
4541 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4542 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4543 }
4544 return rc;
4545}
4546
4547/*
danda9fe0c2010-07-13 18:44:03 +00004548** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004549** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004550**
drh7234c6d2010-06-19 15:10:09 +00004551** The file used to implement shared-memory is in the same directory
4552** as the open database file and has the same name as the open database
4553** file with the "-shm" suffix added. For example, if the database file
4554** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004555** for shared memory will be called "/home/user1/config.db-shm".
4556**
4557** Another approach to is to use files in /dev/shm or /dev/tmp or an
4558** some other tmpfs mount. But if a file in a different directory
4559** from the database file is used, then differing access permissions
4560** or a chroot() might cause two different processes on the same
4561** database to end up using different files for shared memory -
4562** meaning that their memory would not really be shared - resulting
4563** in database corruption. Nevertheless, this tmpfs file usage
4564** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4565** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4566** option results in an incompatible build of SQLite; builds of SQLite
4567** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4568** same database file at the same time, database corruption will likely
4569** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4570** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004571**
4572** When opening a new shared-memory file, if no other instances of that
4573** file are currently open, in this process or in other processes, then
4574** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004575**
4576** If the original database file (pDbFd) is using the "unix-excl" VFS
4577** that means that an exclusive lock is held on the database file and
4578** that no other processes are able to read or write the database. In
4579** that case, we do not really need shared memory. No shared memory
4580** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004581*/
danda9fe0c2010-07-13 18:44:03 +00004582static int unixOpenSharedMemory(unixFile *pDbFd){
4583 struct unixShm *p = 0; /* The connection to be opened */
4584 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004585 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004586 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004587 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004588 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004589
danda9fe0c2010-07-13 18:44:03 +00004590 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004591 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004592 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004593 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004594 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004595
danda9fe0c2010-07-13 18:44:03 +00004596 /* Check to see if a unixShmNode object already exists. Reuse an existing
4597 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004598 */
drh095908e2018-08-13 20:46:18 +00004599 assert( unixFileMutexNotheld(pDbFd) );
drhd9e5c4f2010-05-12 18:01:39 +00004600 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004601 pInode = pDbFd->pInode;
4602 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004603 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004604 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004605#ifndef SQLITE_SHM_DIRECTORY
4606 const char *zBasePath = pDbFd->zPath;
4607#endif
danddb0ac42010-07-14 14:48:58 +00004608
4609 /* Call fstat() to figure out the permissions on the database file. If
4610 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004611 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004612 */
drhf3b1ed02015-12-02 13:11:03 +00004613 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004614 rc = SQLITE_IOERR_FSTAT;
4615 goto shm_open_err;
4616 }
4617
drha4ced192010-07-15 18:32:40 +00004618#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004619 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004620#else
drh4bf66fd2015-02-19 02:43:02 +00004621 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004622#endif
drhf3cdcdc2015-04-29 16:50:28 +00004623 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004624 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004625 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004626 goto shm_open_err;
4627 }
drh9cb5a0d2012-01-05 21:19:54 +00004628 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004629 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004630#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004631 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004632 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4633 (u32)sStat.st_ino, (u32)sStat.st_dev);
4634#else
danf12ba662017-11-07 15:43:52 +00004635 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4636 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004637#endif
drh8820c8d2018-10-02 19:58:08 +00004638 pShmNode->hShm = -1;
drhd91c68f2010-05-14 14:52:25 +00004639 pDbFd->pInode->pShmNode = pShmNode;
4640 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004641 if( sqlite3GlobalConfig.bCoreMutex ){
drh24efa542018-10-02 19:36:40 +00004642 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4643 if( pShmNode->pShmMutex==0 ){
drh97a7e5e2016-04-26 18:58:54 +00004644 rc = SQLITE_NOMEM_BKPT;
4645 goto shm_open_err;
4646 }
drhd91c68f2010-05-14 14:52:25 +00004647 }
drhd9e5c4f2010-05-12 18:01:39 +00004648
drh3cb93392011-03-12 18:10:44 +00004649 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004650 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drhc398c652019-11-22 00:42:01 +00004651 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
4652 (sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004653 }
drh8820c8d2018-10-02 19:58:08 +00004654 if( pShmNode->hShm<0 ){
drhc398c652019-11-22 00:42:01 +00004655 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
4656 (sStat.st_mode&0777));
drh8820c8d2018-10-02 19:58:08 +00004657 if( pShmNode->hShm<0 ){
danf12ba662017-11-07 15:43:52 +00004658 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4659 goto shm_open_err;
4660 }
4661 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004662 }
drhac7c3ac2012-02-11 19:23:48 +00004663
4664 /* If this process is running as root, make sure that the SHM file
4665 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004666 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004667 */
drh8820c8d2018-10-02 19:58:08 +00004668 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004669
dan92c02da2017-11-01 20:59:28 +00004670 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004671 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004672 }
drhd9e5c4f2010-05-12 18:01:39 +00004673 }
4674
drhd91c68f2010-05-14 14:52:25 +00004675 /* Make the new connection a child of the unixShmNode */
4676 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004677#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004678 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004679#endif
drhd91c68f2010-05-14 14:52:25 +00004680 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004681 pDbFd->pShm = p;
4682 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004683
4684 /* The reference count on pShmNode has already been incremented under
4685 ** the cover of the unixEnterMutex() mutex and the pointer from the
4686 ** new (struct unixShm) object to the pShmNode has been set. All that is
4687 ** left to do is to link the new object into the linked list starting
drh24efa542018-10-02 19:36:40 +00004688 ** at pShmNode->pFirst. This must be done while holding the
4689 ** pShmNode->pShmMutex.
dan0668f592010-07-20 18:59:00 +00004690 */
drh24efa542018-10-02 19:36:40 +00004691 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan0668f592010-07-20 18:59:00 +00004692 p->pNext = pShmNode->pFirst;
4693 pShmNode->pFirst = p;
drh24efa542018-10-02 19:36:40 +00004694 sqlite3_mutex_leave(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004695 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004696
4697 /* Jump here on any error */
4698shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004699 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004700 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004701 unixLeaveMutex();
4702 return rc;
4703}
4704
4705/*
danda9fe0c2010-07-13 18:44:03 +00004706** This function is called to obtain a pointer to region iRegion of the
4707** shared-memory associated with the database file fd. Shared-memory regions
4708** are numbered starting from zero. Each shared-memory region is szRegion
4709** bytes in size.
4710**
4711** If an error occurs, an error code is returned and *pp is set to NULL.
4712**
4713** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4714** region has not been allocated (by any client, including one running in a
4715** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4716** bExtend is non-zero and the requested shared-memory region has not yet
4717** been allocated, it is allocated by this function.
4718**
4719** If the shared-memory region has already been allocated or is allocated by
4720** this call as described above, then it is mapped into this processes
4721** address space (if it is not already), *pp is set to point to the mapped
4722** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004723*/
danda9fe0c2010-07-13 18:44:03 +00004724static int unixShmMap(
4725 sqlite3_file *fd, /* Handle open on database file */
4726 int iRegion, /* Region to retrieve */
4727 int szRegion, /* Size of regions */
4728 int bExtend, /* True to extend file if necessary */
4729 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004730){
danda9fe0c2010-07-13 18:44:03 +00004731 unixFile *pDbFd = (unixFile*)fd;
4732 unixShm *p;
4733 unixShmNode *pShmNode;
4734 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004735 int nShmPerMap = unixShmRegionPerMap();
4736 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004737
danda9fe0c2010-07-13 18:44:03 +00004738 /* If the shared-memory file has not yet been opened, open it now. */
4739 if( pDbFd->pShm==0 ){
4740 rc = unixOpenSharedMemory(pDbFd);
4741 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004742 }
drhd9e5c4f2010-05-12 18:01:39 +00004743
danda9fe0c2010-07-13 18:44:03 +00004744 p = pDbFd->pShm;
4745 pShmNode = p->pShmNode;
drh24efa542018-10-02 19:36:40 +00004746 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004747 if( pShmNode->isUnlocked ){
4748 rc = unixLockSharedMemory(pDbFd, pShmNode);
4749 if( rc!=SQLITE_OK ) goto shmpage_out;
4750 pShmNode->isUnlocked = 0;
4751 }
danda9fe0c2010-07-13 18:44:03 +00004752 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004753 assert( pShmNode->pInode==pDbFd->pInode );
drh8820c8d2018-10-02 19:58:08 +00004754 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4755 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004756
dan781e34c2014-03-20 08:59:47 +00004757 /* Minimum number of regions required to be mapped. */
4758 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4759
4760 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004761 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004762 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004763 struct stat sStat; /* Used by fstat() */
4764
4765 pShmNode->szRegion = szRegion;
4766
drh8820c8d2018-10-02 19:58:08 +00004767 if( pShmNode->hShm>=0 ){
drh3cb93392011-03-12 18:10:44 +00004768 /* The requested region is not mapped into this processes address space.
4769 ** Check to see if it has been allocated (i.e. if the wal-index file is
4770 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004771 */
drh8820c8d2018-10-02 19:58:08 +00004772 if( osFstat(pShmNode->hShm, &sStat) ){
drh3cb93392011-03-12 18:10:44 +00004773 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004774 goto shmpage_out;
4775 }
drh3cb93392011-03-12 18:10:44 +00004776
4777 if( sStat.st_size<nByte ){
4778 /* The requested memory region does not exist. If bExtend is set to
4779 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004780 */
dan47a2b4a2013-04-26 16:09:29 +00004781 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004782 goto shmpage_out;
4783 }
dan47a2b4a2013-04-26 16:09:29 +00004784
4785 /* Alternatively, if bExtend is true, extend the file. Do this by
4786 ** writing a single byte to the end of each (OS) page being
4787 ** allocated or extended. Technically, we need only write to the
4788 ** last page in order to extend the file. But writing to all new
4789 ** pages forces the OS to allocate them immediately, which reduces
4790 ** the chances of SIGBUS while accessing the mapped region later on.
4791 */
4792 else{
4793 static const int pgsz = 4096;
4794 int iPg;
4795
4796 /* Write to the last byte of each newly allocated or extended page */
4797 assert( (nByte % pgsz)==0 );
4798 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004799 int x = 0;
drh8820c8d2018-10-02 19:58:08 +00004800 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004801 const char *zFile = pShmNode->zFilename;
4802 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4803 goto shmpage_out;
4804 }
4805 }
drh3cb93392011-03-12 18:10:44 +00004806 }
4807 }
danda9fe0c2010-07-13 18:44:03 +00004808 }
4809
4810 /* Map the requested memory region into this processes address space. */
4811 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004812 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004813 );
4814 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004815 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004816 goto shmpage_out;
4817 }
4818 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004819 while( pShmNode->nRegion<nReqRegion ){
4820 int nMap = szRegion*nShmPerMap;
4821 int i;
drh3cb93392011-03-12 18:10:44 +00004822 void *pMem;
drh8820c8d2018-10-02 19:58:08 +00004823 if( pShmNode->hShm>=0 ){
dan781e34c2014-03-20 08:59:47 +00004824 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004825 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh8820c8d2018-10-02 19:58:08 +00004826 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004827 );
4828 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004829 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004830 goto shmpage_out;
4831 }
4832 }else{
drhb6c4d592018-10-11 02:39:11 +00004833 pMem = sqlite3_malloc64(nMap);
drh3cb93392011-03-12 18:10:44 +00004834 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004835 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004836 goto shmpage_out;
4837 }
drhb6c4d592018-10-11 02:39:11 +00004838 memset(pMem, 0, nMap);
danda9fe0c2010-07-13 18:44:03 +00004839 }
dan781e34c2014-03-20 08:59:47 +00004840
4841 for(i=0; i<nShmPerMap; i++){
4842 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4843 }
4844 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004845 }
4846 }
4847
4848shmpage_out:
4849 if( pShmNode->nRegion>iRegion ){
4850 *pp = pShmNode->apRegion[iRegion];
4851 }else{
4852 *pp = 0;
4853 }
drh66dfec8b2011-06-01 20:01:49 +00004854 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
drh24efa542018-10-02 19:36:40 +00004855 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004856 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004857}
4858
4859/*
dan8337da62020-08-28 19:27:15 +00004860** Check that the pShmNode->aLock[] array comports with the locking bitmasks
4861** held by each client. Return true if it does, or false otherwise. This
4862** is to be used in an assert(). e.g.
4863**
4864** assert( assertLockingArrayOk(pShmNode) );
4865*/
4866#ifdef SQLITE_DEBUG
4867static int assertLockingArrayOk(unixShmNode *pShmNode){
4868 unixShm *pX;
4869 int aLock[SQLITE_SHM_NLOCK];
4870 assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
4871
4872 memset(aLock, 0, sizeof(aLock));
4873 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4874 int i;
4875 for(i=0; i<SQLITE_SHM_NLOCK; i++){
4876 if( pX->exclMask & (1<<i) ){
4877 assert( aLock[i]==0 );
4878 aLock[i] = -1;
4879 }else if( pX->sharedMask & (1<<i) ){
4880 assert( aLock[i]>=0 );
4881 aLock[i]++;
4882 }
4883 }
4884 }
4885
4886 assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
4887 return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
4888}
4889#endif
4890
4891/*
drhd9e5c4f2010-05-12 18:01:39 +00004892** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004893**
4894** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4895** different here than in posix. In xShmLock(), one can go from unlocked
4896** to shared and back or from unlocked to exclusive and back. But one may
4897** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004898*/
4899static int unixShmLock(
4900 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004901 int ofst, /* First lock to acquire or release */
4902 int n, /* Number of locks to acquire or release */
4903 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004904){
drh73b64e42010-05-30 19:55:15 +00004905 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4906 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
drh73b64e42010-05-30 19:55:15 +00004907 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4908 int rc = SQLITE_OK; /* Result code */
4909 u16 mask; /* Mask of locks to take or release */
dan8337da62020-08-28 19:27:15 +00004910 int *aLock = pShmNode->aLock;
drhd9e5c4f2010-05-12 18:01:39 +00004911
drhd91c68f2010-05-14 14:52:25 +00004912 assert( pShmNode==pDbFd->pInode->pShmNode );
4913 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004914 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004915 assert( n>=1 );
4916 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4917 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4918 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4919 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4920 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh8820c8d2018-10-02 19:58:08 +00004921 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4922 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004923
dan58021b22020-05-05 20:30:07 +00004924 /* Check that, if this to be a blocking lock, no locks that occur later
4925 ** in the following list than the lock being obtained are already held:
dan97ccc1b2020-03-27 17:23:17 +00004926 **
4927 ** 1. Checkpointer lock (ofst==1).
dan58021b22020-05-05 20:30:07 +00004928 ** 2. Write lock (ofst==0).
dan97ccc1b2020-03-27 17:23:17 +00004929 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
dan97ccc1b2020-03-27 17:23:17 +00004930 **
4931 ** In other words, if this is a blocking lock, none of the locks that
4932 ** occur later in the above list than the lock being obtained may be
dand31fcd42020-05-29 11:07:20 +00004933 ** held.
4934 **
4935 ** It is not permitted to block on the RECOVER lock.
4936 */
dan97ccc1b2020-03-27 17:23:17 +00004937#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
dan58021b22020-05-05 20:30:07 +00004938 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
4939 (ofst!=2) /* not RECOVER */
dan58021b22020-05-05 20:30:07 +00004940 && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
4941 && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
4942 && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
4943 ));
dan97ccc1b2020-03-27 17:23:17 +00004944#endif
4945
drhc99597c2010-05-31 01:41:15 +00004946 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004947 assert( n>1 || mask==(1<<ofst) );
drh24efa542018-10-02 19:36:40 +00004948 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan8337da62020-08-28 19:27:15 +00004949 assert( assertLockingArrayOk(pShmNode) );
drh73b64e42010-05-30 19:55:15 +00004950 if( flags & SQLITE_SHM_UNLOCK ){
dan6acdee62020-08-28 20:01:06 +00004951 if( (p->exclMask|p->sharedMask) & mask ){
4952 int ii;
4953 int bUnlock = 1;
drh73b64e42010-05-30 19:55:15 +00004954
dan6acdee62020-08-28 20:01:06 +00004955 for(ii=ofst; ii<ofst+n; ii++){
4956 if( aLock[ii]>((p->sharedMask & (1<<ii)) ? 1 : 0) ){
4957 bUnlock = 0;
4958 }
dan8337da62020-08-28 19:27:15 +00004959 }
drh73b64e42010-05-30 19:55:15 +00004960
dan6acdee62020-08-28 20:01:06 +00004961 if( bUnlock ){
4962 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
4963 if( rc==SQLITE_OK ){
4964 memset(&aLock[ofst], 0, sizeof(int)*n);
4965 }
drh78043e82020-11-06 16:48:55 +00004966 }else if( ALWAYS(p->sharedMask & (1<<ofst)) ){
dan6acdee62020-08-28 20:01:06 +00004967 assert( n==1 && aLock[ofst]>1 );
4968 aLock[ofst]--;
4969 }
4970
4971 /* Undo the local locks */
dan8337da62020-08-28 19:27:15 +00004972 if( rc==SQLITE_OK ){
dan6acdee62020-08-28 20:01:06 +00004973 p->exclMask &= ~mask;
4974 p->sharedMask &= ~mask;
4975 }
drhd9e5c4f2010-05-12 18:01:39 +00004976 }
drh73b64e42010-05-30 19:55:15 +00004977 }else if( flags & SQLITE_SHM_SHARED ){
dan8337da62020-08-28 19:27:15 +00004978 assert( n==1 );
4979 assert( (p->exclMask & (1<<ofst))==0 );
4980 if( (p->sharedMask & mask)==0 ){
4981 if( aLock[ofst]<0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004982 rc = SQLITE_BUSY;
dan8337da62020-08-28 19:27:15 +00004983 }else if( aLock[ofst]==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004984 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004985 }
drh73b64e42010-05-30 19:55:15 +00004986
dan8337da62020-08-28 19:27:15 +00004987 /* Get the local shared locks */
4988 if( rc==SQLITE_OK ){
4989 p->sharedMask |= mask;
4990 aLock[ofst]++;
4991 }
drh73b64e42010-05-30 19:55:15 +00004992 }
4993 }else{
4994 /* Make sure no sibling connections hold locks that will block this
dan8337da62020-08-28 19:27:15 +00004995 ** lock. If any do, return SQLITE_BUSY right away. */
4996 int ii;
4997 for(ii=ofst; ii<ofst+n; ii++){
4998 assert( (p->sharedMask & mask)==0 );
drh78043e82020-11-06 16:48:55 +00004999 if( ALWAYS((p->exclMask & (1<<ii))==0) && aLock[ii] ){
drh73b64e42010-05-30 19:55:15 +00005000 rc = SQLITE_BUSY;
5001 break;
5002 }
5003 }
dan8337da62020-08-28 19:27:15 +00005004
5005 /* Get the exclusive locks at the system level. Then if successful
5006 ** also update the in-memory values. */
drh73b64e42010-05-30 19:55:15 +00005007 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00005008 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00005009 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00005010 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00005011 p->exclMask |= mask;
dan8337da62020-08-28 19:27:15 +00005012 for(ii=ofst; ii<ofst+n; ii++){
5013 aLock[ii] = -1;
5014 }
drhd9e5c4f2010-05-12 18:01:39 +00005015 }
drhd9e5c4f2010-05-12 18:01:39 +00005016 }
5017 }
dan8337da62020-08-28 19:27:15 +00005018 assert( assertLockingArrayOk(pShmNode) );
drh24efa542018-10-02 19:36:40 +00005019 sqlite3_mutex_leave(pShmNode->pShmMutex);
drh20e1f082010-05-31 16:10:12 +00005020 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00005021 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00005022 return rc;
5023}
5024
drh286a2882010-05-20 23:51:06 +00005025/*
5026** Implement a memory barrier or memory fence on shared memory.
5027**
5028** All loads and stores begun before the barrier must complete before
5029** any load or store begun after the barrier.
5030*/
5031static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00005032 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00005033){
drhff828942010-06-26 21:34:06 +00005034 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00005035 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
dana86acc22018-09-12 20:32:19 +00005036 assert( fd->pMethods->xLock==nolockLock
5037 || unixFileMutexNotheld((unixFile*)fd)
5038 );
drh22c733d2015-09-24 12:40:43 +00005039 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00005040 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00005041}
5042
dan18801912010-06-14 14:07:50 +00005043/*
danda9fe0c2010-07-13 18:44:03 +00005044** Close a connection to shared-memory. Delete the underlying
5045** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00005046**
5047** If there is no shared memory associated with the connection then this
5048** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00005049*/
danda9fe0c2010-07-13 18:44:03 +00005050static int unixShmUnmap(
5051 sqlite3_file *fd, /* The underlying database file */
5052 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00005053){
danda9fe0c2010-07-13 18:44:03 +00005054 unixShm *p; /* The connection to be closed */
5055 unixShmNode *pShmNode; /* The underlying shared-memory file */
5056 unixShm **pp; /* For looping over sibling connections */
5057 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00005058
danda9fe0c2010-07-13 18:44:03 +00005059 pDbFd = (unixFile*)fd;
5060 p = pDbFd->pShm;
5061 if( p==0 ) return SQLITE_OK;
5062 pShmNode = p->pShmNode;
5063
5064 assert( pShmNode==pDbFd->pInode->pShmNode );
5065 assert( pShmNode->pInode==pDbFd->pInode );
5066
5067 /* Remove connection p from the set of connections associated
5068 ** with pShmNode */
drh24efa542018-10-02 19:36:40 +00005069 sqlite3_mutex_enter(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00005070 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
5071 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00005072
danda9fe0c2010-07-13 18:44:03 +00005073 /* Free the connection p */
5074 sqlite3_free(p);
5075 pDbFd->pShm = 0;
drh24efa542018-10-02 19:36:40 +00005076 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00005077
5078 /* If pShmNode->nRef has reached 0, then close the underlying
5079 ** shared-memory file, too */
drh095908e2018-08-13 20:46:18 +00005080 assert( unixFileMutexNotheld(pDbFd) );
danda9fe0c2010-07-13 18:44:03 +00005081 unixEnterMutex();
5082 assert( pShmNode->nRef>0 );
5083 pShmNode->nRef--;
5084 if( pShmNode->nRef==0 ){
drh8820c8d2018-10-02 19:58:08 +00005085 if( deleteFlag && pShmNode->hShm>=0 ){
drh4bf66fd2015-02-19 02:43:02 +00005086 osUnlink(pShmNode->zFilename);
5087 }
danda9fe0c2010-07-13 18:44:03 +00005088 unixShmPurge(pDbFd);
5089 }
5090 unixLeaveMutex();
5091
5092 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00005093}
drh286a2882010-05-20 23:51:06 +00005094
danda9fe0c2010-07-13 18:44:03 +00005095
drhd9e5c4f2010-05-12 18:01:39 +00005096#else
drh6b017cc2010-06-14 18:01:46 +00005097# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00005098# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00005099# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00005100# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00005101#endif /* #ifndef SQLITE_OMIT_WAL */
5102
mistachkine98844f2013-08-24 00:59:24 +00005103#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00005104/*
danaef49d72013-03-25 16:28:54 +00005105** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00005106*/
danf23da962013-03-23 21:00:41 +00005107static void unixUnmapfile(unixFile *pFd){
5108 assert( pFd->nFetchOut==0 );
5109 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00005110 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00005111 pFd->pMapRegion = 0;
5112 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00005113 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00005114 }
5115}
dan5d8a1372013-03-19 19:28:06 +00005116
danaef49d72013-03-25 16:28:54 +00005117/*
dane6ecd662013-04-01 17:56:59 +00005118** Attempt to set the size of the memory mapping maintained by file
5119** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5120**
5121** If successful, this function sets the following variables:
5122**
5123** unixFile.pMapRegion
5124** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00005125** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00005126**
5127** If unsuccessful, an error message is logged via sqlite3_log() and
5128** the three variables above are zeroed. In this case SQLite should
5129** continue accessing the database using the xRead() and xWrite()
5130** methods.
5131*/
5132static void unixRemapfile(
5133 unixFile *pFd, /* File descriptor object */
5134 i64 nNew /* Required mapping size */
5135){
dan4ff7bc42013-04-02 12:04:09 +00005136 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00005137 int h = pFd->h; /* File descriptor open on db file */
5138 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00005139 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00005140 u8 *pNew = 0; /* Location of new mapping */
5141 int flags = PROT_READ; /* Flags to pass to mmap() */
5142
5143 assert( pFd->nFetchOut==0 );
5144 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00005145 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00005146 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00005147 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00005148 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00005149
danfe33e392015-11-17 20:56:06 +00005150#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00005151 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00005152#endif
dane6ecd662013-04-01 17:56:59 +00005153
5154 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00005155#if HAVE_MREMAP
5156 i64 nReuse = pFd->mmapSize;
5157#else
danbc760632014-03-20 09:42:09 +00005158 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00005159 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00005160#endif
dane6ecd662013-04-01 17:56:59 +00005161 u8 *pReq = &pOrig[nReuse];
5162
5163 /* Unmap any pages of the existing mapping that cannot be reused. */
5164 if( nReuse!=nOrig ){
5165 osMunmap(pReq, nOrig-nReuse);
5166 }
5167
5168#if HAVE_MREMAP
5169 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00005170 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00005171#else
5172 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5173 if( pNew!=MAP_FAILED ){
5174 if( pNew!=pReq ){
5175 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00005176 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00005177 }else{
5178 pNew = pOrig;
5179 }
5180 }
5181#endif
5182
dan48ccef82013-04-02 20:55:01 +00005183 /* The attempt to extend the existing mapping failed. Free it. */
5184 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00005185 osMunmap(pOrig, nReuse);
5186 }
5187 }
5188
5189 /* If pNew is still NULL, try to create an entirely new mapping. */
5190 if( pNew==0 ){
5191 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00005192 }
5193
dan4ff7bc42013-04-02 12:04:09 +00005194 if( pNew==MAP_FAILED ){
5195 pNew = 0;
5196 nNew = 0;
5197 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5198
5199 /* If the mmap() above failed, assume that all subsequent mmap() calls
5200 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5201 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00005202 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00005203 }
dane6ecd662013-04-01 17:56:59 +00005204 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00005205 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00005206}
5207
5208/*
danaef49d72013-03-25 16:28:54 +00005209** Memory map or remap the file opened by file-descriptor pFd (if the file
5210** is already mapped, the existing mapping is replaced by the new). Or, if
5211** there already exists a mapping for this file, and there are still
5212** outstanding xFetch() references to it, this function is a no-op.
5213**
5214** If parameter nByte is non-negative, then it is the requested size of
5215** the mapping to create. Otherwise, if nByte is less than zero, then the
5216** requested size is the size of the file on disk. The actual size of the
5217** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00005218** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00005219**
5220** SQLITE_OK is returned if no error occurs (even if the mapping is not
5221** recreated as a result of outstanding references) or an SQLite error
5222** code otherwise.
5223*/
drhf3b1ed02015-12-02 13:11:03 +00005224static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00005225 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00005226 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005227 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5228
5229 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00005230 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00005231 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00005232 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00005233 }
drh3044b512014-06-16 16:41:52 +00005234 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00005235 }
drh9b4c59f2013-04-15 17:03:42 +00005236 if( nMap>pFd->mmapSizeMax ){
5237 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00005238 }
5239
drh333e6ca2015-12-02 15:44:39 +00005240 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005241 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00005242 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00005243 }
5244
danf23da962013-03-23 21:00:41 +00005245 return SQLITE_OK;
5246}
mistachkine98844f2013-08-24 00:59:24 +00005247#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00005248
danaef49d72013-03-25 16:28:54 +00005249/*
5250** If possible, return a pointer to a mapping of file fd starting at offset
5251** iOff. The mapping must be valid for at least nAmt bytes.
5252**
5253** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5254** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5255** Finally, if an error does occur, return an SQLite error code. The final
5256** value of *pp is undefined in this case.
5257**
5258** If this function does return a pointer, the caller must eventually
5259** release the reference by calling unixUnfetch().
5260*/
danf23da962013-03-23 21:00:41 +00005261static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00005262#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00005263 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00005264#endif
danf23da962013-03-23 21:00:41 +00005265 *pp = 0;
5266
drh9b4c59f2013-04-15 17:03:42 +00005267#if SQLITE_MAX_MMAP_SIZE>0
5268 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00005269 if( pFd->pMapRegion==0 ){
5270 int rc = unixMapfile(pFd, -1);
5271 if( rc!=SQLITE_OK ) return rc;
5272 }
5273 if( pFd->mmapSize >= iOff+nAmt ){
5274 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5275 pFd->nFetchOut++;
5276 }
5277 }
drh6e0b6d52013-04-09 16:19:20 +00005278#endif
danf23da962013-03-23 21:00:41 +00005279 return SQLITE_OK;
5280}
5281
danaef49d72013-03-25 16:28:54 +00005282/*
dandf737fe2013-03-25 17:00:24 +00005283** If the third argument is non-NULL, then this function releases a
5284** reference obtained by an earlier call to unixFetch(). The second
5285** argument passed to this function must be the same as the corresponding
5286** argument that was passed to the unixFetch() invocation.
5287**
5288** Or, if the third argument is NULL, then this function is being called
5289** to inform the VFS layer that, according to POSIX, any existing mapping
5290** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005291*/
dandf737fe2013-03-25 17:00:24 +00005292static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005293#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005294 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005295 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005296
danaef49d72013-03-25 16:28:54 +00005297 /* If p==0 (unmap the entire file) then there must be no outstanding
5298 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5299 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005300 assert( (p==0)==(pFd->nFetchOut==0) );
5301
dandf737fe2013-03-25 17:00:24 +00005302 /* If p!=0, it must match the iOff value. */
5303 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5304
danf23da962013-03-23 21:00:41 +00005305 if( p ){
5306 pFd->nFetchOut--;
5307 }else{
5308 unixUnmapfile(pFd);
5309 }
5310
5311 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005312#else
5313 UNUSED_PARAMETER(fd);
5314 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005315 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005316#endif
danf23da962013-03-23 21:00:41 +00005317 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005318}
5319
5320/*
drh734c9862008-11-28 15:37:20 +00005321** Here ends the implementation of all sqlite3_file methods.
5322**
5323********************** End sqlite3_file Methods *******************************
5324******************************************************************************/
5325
5326/*
drh6b9d6dd2008-12-03 19:34:47 +00005327** This division contains definitions of sqlite3_io_methods objects that
5328** implement various file locking strategies. It also contains definitions
5329** of "finder" functions. A finder-function is used to locate the appropriate
5330** sqlite3_io_methods object for a particular database file. The pAppData
5331** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5332** the correct finder-function for that VFS.
5333**
5334** Most finder functions return a pointer to a fixed sqlite3_io_methods
5335** object. The only interesting finder-function is autolockIoFinder, which
5336** looks at the filesystem type and tries to guess the best locking
5337** strategy from that.
5338**
peter.d.reid60ec9142014-09-06 16:39:46 +00005339** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005340**
5341** (1) The real finder-function named "FImpt()".
5342**
dane946c392009-08-22 11:39:46 +00005343** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005344**
5345**
5346** A pointer to the F pointer is used as the pAppData value for VFS
5347** objects. We have to do this instead of letting pAppData point
5348** directly at the finder-function since C90 rules prevent a void*
5349** from be cast into a function pointer.
5350**
drh6b9d6dd2008-12-03 19:34:47 +00005351**
drh7708e972008-11-29 00:56:52 +00005352** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005353**
drh7708e972008-11-29 00:56:52 +00005354** * A constant sqlite3_io_methods object call METHOD that has locking
5355** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5356**
5357** * An I/O method finder function called FINDER that returns a pointer
5358** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005359*/
drhe6d41732015-02-21 00:49:00 +00005360#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005361static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005362 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005363 CLOSE, /* xClose */ \
5364 unixRead, /* xRead */ \
5365 unixWrite, /* xWrite */ \
5366 unixTruncate, /* xTruncate */ \
5367 unixSync, /* xSync */ \
5368 unixFileSize, /* xFileSize */ \
5369 LOCK, /* xLock */ \
5370 UNLOCK, /* xUnlock */ \
5371 CKLOCK, /* xCheckReservedLock */ \
5372 unixFileControl, /* xFileControl */ \
5373 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005374 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005375 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005376 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005377 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005378 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005379 unixFetch, /* xFetch */ \
5380 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005381}; \
drh0c2694b2009-09-03 16:23:44 +00005382static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5383 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005384 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005385} \
drh0c2694b2009-09-03 16:23:44 +00005386static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005387 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005388
5389/*
5390** Here are all of the sqlite3_io_methods objects for each of the
5391** locking strategies. Functions that return pointers to these methods
5392** are also created.
5393*/
5394IOMETHODS(
5395 posixIoFinder, /* Finder function name */
5396 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005397 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005398 unixClose, /* xClose method */
5399 unixLock, /* xLock method */
5400 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005401 unixCheckReservedLock, /* xCheckReservedLock method */
5402 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005403)
drh7708e972008-11-29 00:56:52 +00005404IOMETHODS(
5405 nolockIoFinder, /* Finder function name */
5406 nolockIoMethods, /* sqlite3_io_methods object name */
drh3e2c8422018-08-13 11:32:07 +00005407 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005408 nolockClose, /* xClose method */
5409 nolockLock, /* xLock method */
5410 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005411 nolockCheckReservedLock, /* xCheckReservedLock method */
5412 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005413)
drh7708e972008-11-29 00:56:52 +00005414IOMETHODS(
5415 dotlockIoFinder, /* Finder function name */
5416 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005417 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005418 dotlockClose, /* xClose method */
5419 dotlockLock, /* xLock method */
5420 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005421 dotlockCheckReservedLock, /* xCheckReservedLock method */
5422 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005423)
drh7708e972008-11-29 00:56:52 +00005424
drhe89b2912015-03-03 20:42:01 +00005425#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005426IOMETHODS(
5427 flockIoFinder, /* Finder function name */
5428 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005429 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005430 flockClose, /* xClose method */
5431 flockLock, /* xLock method */
5432 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005433 flockCheckReservedLock, /* xCheckReservedLock method */
5434 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005435)
drh7708e972008-11-29 00:56:52 +00005436#endif
5437
drh6c7d5c52008-11-21 20:32:33 +00005438#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005439IOMETHODS(
5440 semIoFinder, /* Finder function name */
5441 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005442 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005443 semXClose, /* xClose method */
5444 semXLock, /* xLock method */
5445 semXUnlock, /* xUnlock method */
5446 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005447 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005448)
aswiftaebf4132008-11-21 00:10:35 +00005449#endif
drh7708e972008-11-29 00:56:52 +00005450
drhd2cb50b2009-01-09 21:41:17 +00005451#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005452IOMETHODS(
5453 afpIoFinder, /* Finder function name */
5454 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005455 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005456 afpClose, /* xClose method */
5457 afpLock, /* xLock method */
5458 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005459 afpCheckReservedLock, /* xCheckReservedLock method */
5460 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005461)
drh715ff302008-12-03 22:32:44 +00005462#endif
5463
5464/*
5465** The proxy locking method is a "super-method" in the sense that it
5466** opens secondary file descriptors for the conch and lock files and
5467** it uses proxy, dot-file, AFP, and flock() locking methods on those
5468** secondary files. For this reason, the division that implements
5469** proxy locking is located much further down in the file. But we need
5470** to go ahead and define the sqlite3_io_methods and finder function
5471** for proxy locking here. So we forward declare the I/O methods.
5472*/
drhd2cb50b2009-01-09 21:41:17 +00005473#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005474static int proxyClose(sqlite3_file*);
5475static int proxyLock(sqlite3_file*, int);
5476static int proxyUnlock(sqlite3_file*, int);
5477static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005478IOMETHODS(
5479 proxyIoFinder, /* Finder function name */
5480 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005481 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005482 proxyClose, /* xClose method */
5483 proxyLock, /* xLock method */
5484 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005485 proxyCheckReservedLock, /* xCheckReservedLock method */
5486 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005487)
aswiftaebf4132008-11-21 00:10:35 +00005488#endif
drh7708e972008-11-29 00:56:52 +00005489
drh7ed97b92010-01-20 13:07:21 +00005490/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5491#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5492IOMETHODS(
5493 nfsIoFinder, /* Finder function name */
5494 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005495 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005496 unixClose, /* xClose method */
5497 unixLock, /* xLock method */
5498 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005499 unixCheckReservedLock, /* xCheckReservedLock method */
5500 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005501)
5502#endif
drh7708e972008-11-29 00:56:52 +00005503
drhd2cb50b2009-01-09 21:41:17 +00005504#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005505/*
drh6b9d6dd2008-12-03 19:34:47 +00005506** This "finder" function attempts to determine the best locking strategy
5507** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005508** object that implements that strategy.
5509**
5510** This is for MacOSX only.
5511*/
drh1875f7a2008-12-08 18:19:17 +00005512static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005513 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005514 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005515){
5516 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005517 const char *zFilesystem; /* Filesystem type name */
5518 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005519 } aMap[] = {
5520 { "hfs", &posixIoMethods },
5521 { "ufs", &posixIoMethods },
5522 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005523 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005524 { "webdav", &nolockIoMethods },
5525 { 0, 0 }
5526 };
5527 int i;
5528 struct statfs fsInfo;
5529 struct flock lockInfo;
5530
5531 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005532 /* If filePath==NULL that means we are dealing with a transient file
5533 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005534 return &nolockIoMethods;
5535 }
5536 if( statfs(filePath, &fsInfo) != -1 ){
5537 if( fsInfo.f_flags & MNT_RDONLY ){
5538 return &nolockIoMethods;
5539 }
5540 for(i=0; aMap[i].zFilesystem; i++){
5541 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5542 return aMap[i].pMethods;
5543 }
5544 }
5545 }
5546
5547 /* Default case. Handles, amongst others, "nfs".
5548 ** Test byte-range lock using fcntl(). If the call succeeds,
5549 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005550 */
drh7708e972008-11-29 00:56:52 +00005551 lockInfo.l_len = 1;
5552 lockInfo.l_start = 0;
5553 lockInfo.l_whence = SEEK_SET;
5554 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005555 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005556 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5557 return &nfsIoMethods;
5558 } else {
5559 return &posixIoMethods;
5560 }
drh7708e972008-11-29 00:56:52 +00005561 }else{
5562 return &dotlockIoMethods;
5563 }
5564}
drh0c2694b2009-09-03 16:23:44 +00005565static const sqlite3_io_methods
5566 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005567
drhd2cb50b2009-01-09 21:41:17 +00005568#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005569
drhe89b2912015-03-03 20:42:01 +00005570#if OS_VXWORKS
5571/*
5572** This "finder" function for VxWorks checks to see if posix advisory
5573** locking works. If it does, then that is what is used. If it does not
5574** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005575*/
drhe89b2912015-03-03 20:42:01 +00005576static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005577 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005578 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005579){
5580 struct flock lockInfo;
5581
5582 if( !filePath ){
5583 /* If filePath==NULL that means we are dealing with a transient file
5584 ** that does not need to be locked. */
5585 return &nolockIoMethods;
5586 }
5587
5588 /* Test if fcntl() is supported and use POSIX style locks.
5589 ** Otherwise fall back to the named semaphore method.
5590 */
5591 lockInfo.l_len = 1;
5592 lockInfo.l_start = 0;
5593 lockInfo.l_whence = SEEK_SET;
5594 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005595 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005596 return &posixIoMethods;
5597 }else{
5598 return &semIoMethods;
5599 }
5600}
drh0c2694b2009-09-03 16:23:44 +00005601static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005602 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005603
drhe89b2912015-03-03 20:42:01 +00005604#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005605
drh7708e972008-11-29 00:56:52 +00005606/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005607** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005608*/
drh0c2694b2009-09-03 16:23:44 +00005609typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005610
aswiftaebf4132008-11-21 00:10:35 +00005611
drh734c9862008-11-28 15:37:20 +00005612/****************************************************************************
5613**************************** sqlite3_vfs methods ****************************
5614**
5615** This division contains the implementation of methods on the
5616** sqlite3_vfs object.
5617*/
5618
danielk1977a3d4c882007-03-23 10:08:38 +00005619/*
danielk1977e339d652008-06-28 11:23:00 +00005620** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005621*/
5622static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005623 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005624 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005625 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005626 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005627 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005628){
drh7708e972008-11-29 00:56:52 +00005629 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005630 unixFile *pNew = (unixFile *)pId;
5631 int rc = SQLITE_OK;
5632
drh8af6c222010-05-14 12:43:01 +00005633 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005634
drhb07028f2011-10-14 21:49:18 +00005635 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005636 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005637
drh308c2a52010-05-14 11:30:18 +00005638 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005639 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005640 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005641 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005642 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005643#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005644 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005645#endif
drhc02a43a2012-01-10 23:18:38 +00005646 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5647 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005648 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005649 }
drh503a6862013-03-01 01:07:17 +00005650 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005651 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005652 }
drh339eb0b2008-03-07 15:34:11 +00005653
drh6c7d5c52008-11-21 20:32:33 +00005654#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005655 pNew->pId = vxworksFindFileId(zFilename);
5656 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005657 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005658 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005659 }
5660#endif
5661
drhc02a43a2012-01-10 23:18:38 +00005662 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005663 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005664 }else{
drh0c2694b2009-09-03 16:23:44 +00005665 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005666#if SQLITE_ENABLE_LOCKING_STYLE
5667 /* Cache zFilename in the locking context (AFP and dotlock override) for
5668 ** proxyLock activation is possible (remote proxy is based on db name)
5669 ** zFilename remains valid until file is closed, to support */
5670 pNew->lockingContext = (void*)zFilename;
5671#endif
drhda0e7682008-07-30 15:27:54 +00005672 }
danielk1977e339d652008-06-28 11:23:00 +00005673
drh7ed97b92010-01-20 13:07:21 +00005674 if( pLockingStyle == &posixIoMethods
5675#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5676 || pLockingStyle == &nfsIoMethods
5677#endif
5678 ){
drh7708e972008-11-29 00:56:52 +00005679 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005680 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005681 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005682 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005683 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005684 ** in two scenarios:
5685 **
5686 ** (a) A call to fstat() failed.
5687 ** (b) A malloc failed.
5688 **
5689 ** Scenario (b) may only occur if the process is holding no other
5690 ** file descriptors open on the same file. If there were other file
5691 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005692 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005693 ** handle h - as it is guaranteed that no posix locks will be released
5694 ** by doing so.
5695 **
5696 ** If scenario (a) caused the error then things are not so safe. The
5697 ** implicit assumption here is that if fstat() fails, things are in
5698 ** such bad shape that dropping a lock or two doesn't matter much.
5699 */
drh0e9365c2011-03-02 02:08:13 +00005700 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005701 h = -1;
5702 }
drh7708e972008-11-29 00:56:52 +00005703 unixLeaveMutex();
5704 }
danielk1977e339d652008-06-28 11:23:00 +00005705
drhd2cb50b2009-01-09 21:41:17 +00005706#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005707 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005708 /* AFP locking uses the file path so it needs to be included in
5709 ** the afpLockingContext.
5710 */
5711 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005712 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005713 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005714 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005715 }else{
5716 /* NB: zFilename exists and remains valid until the file is closed
5717 ** according to requirement F11141. So we do not need to make a
5718 ** copy of the filename. */
5719 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005720 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005721 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005722 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005723 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005724 if( rc!=SQLITE_OK ){
5725 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005726 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005727 h = -1;
5728 }
drh7708e972008-11-29 00:56:52 +00005729 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005730 }
drh7708e972008-11-29 00:56:52 +00005731 }
5732#endif
danielk1977e339d652008-06-28 11:23:00 +00005733
drh7708e972008-11-29 00:56:52 +00005734 else if( pLockingStyle == &dotlockIoMethods ){
5735 /* Dotfile locking uses the file path so it needs to be included in
5736 ** the dotlockLockingContext
5737 */
5738 char *zLockFile;
5739 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005740 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005741 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005742 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005743 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005744 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005745 }else{
5746 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005747 }
drh7708e972008-11-29 00:56:52 +00005748 pNew->lockingContext = zLockFile;
5749 }
danielk1977e339d652008-06-28 11:23:00 +00005750
drh6c7d5c52008-11-21 20:32:33 +00005751#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005752 else if( pLockingStyle == &semIoMethods ){
5753 /* Named semaphore locking uses the file path so it needs to be
5754 ** included in the semLockingContext
5755 */
5756 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005757 rc = findInodeInfo(pNew, &pNew->pInode);
5758 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5759 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005760 int n;
drh2238dcc2009-08-27 17:56:20 +00005761 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005762 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005763 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005764 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005765 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5766 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005767 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005768 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005769 }
chw97185482008-11-17 08:05:31 +00005770 }
drh7708e972008-11-29 00:56:52 +00005771 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005772 }
drh7708e972008-11-29 00:56:52 +00005773#endif
aswift5b1a2562008-08-22 00:22:35 +00005774
drh4bf66fd2015-02-19 02:43:02 +00005775 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005776#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005777 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005778 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005779 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005780 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005781 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005782 }
chw97185482008-11-17 08:05:31 +00005783#endif
danielk1977e339d652008-06-28 11:23:00 +00005784 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005785 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005786 }else{
drh0c52f5a2020-07-24 09:17:42 +00005787 pId->pMethods = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005788 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005789 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005790 }
danielk1977e339d652008-06-28 11:23:00 +00005791 return rc;
drh054889e2005-11-30 03:20:31 +00005792}
drh9c06c952005-11-26 00:25:00 +00005793
danielk1977ad94b582007-08-20 06:44:22 +00005794/*
drh8b3cf822010-06-01 21:02:51 +00005795** Return the name of a directory in which to put temporary files.
5796** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005797*/
drh7234c6d2010-06-19 15:10:09 +00005798static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005799 static const char *azDirs[] = {
5800 0,
aswiftaebf4132008-11-21 00:10:35 +00005801 0,
danielk197717b90b52008-06-06 11:11:25 +00005802 "/var/tmp",
5803 "/usr/tmp",
5804 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005805 "."
danielk197717b90b52008-06-06 11:11:25 +00005806 };
drh2aab11f2016-04-29 20:30:56 +00005807 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005808 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005809 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005810
drhb7e50ad2015-11-28 21:49:53 +00005811 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5812 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005813 while(1){
5814 if( zDir!=0
5815 && osStat(zDir, &buf)==0
5816 && S_ISDIR(buf.st_mode)
5817 && osAccess(zDir, 03)==0
5818 ){
5819 return zDir;
5820 }
5821 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5822 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005823 }
drh7694e062016-04-21 23:37:24 +00005824 return 0;
drh8b3cf822010-06-01 21:02:51 +00005825}
5826
5827/*
5828** Create a temporary file name in zBuf. zBuf must be allocated
5829** by the calling process and must be big enough to hold at least
5830** pVfs->mxPathname bytes.
5831*/
5832static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005833 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005834 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005835
5836 /* It's odd to simulate an io-error here, but really this is just
5837 ** using the io-error infrastructure to test that SQLite handles this
5838 ** function failing.
5839 */
drh7694e062016-04-21 23:37:24 +00005840 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005841 SimulateIOError( return SQLITE_IOERR );
5842
drh7234c6d2010-06-19 15:10:09 +00005843 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005844 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005845 do{
drh970942e2015-11-25 23:13:14 +00005846 u64 r;
5847 sqlite3_randomness(sizeof(r), &r);
5848 assert( nBuf>2 );
5849 zBuf[nBuf-2] = 0;
5850 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5851 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005852 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005853 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005854 return SQLITE_OK;
5855}
5856
drhd2cb50b2009-01-09 21:41:17 +00005857#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005858/*
5859** Routine to transform a unixFile into a proxy-locking unixFile.
5860** Implementation in the proxy-lock division, but used by unixOpen()
5861** if SQLITE_PREFER_PROXY_LOCKING is defined.
5862*/
5863static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005864#endif
drhc66d5b62008-12-03 22:48:32 +00005865
dan08da86a2009-08-21 17:18:03 +00005866/*
5867** Search for an unused file descriptor that was opened on the database
drh067b92b2020-06-19 15:24:12 +00005868** file (not a journal or super-journal file) identified by pathname
dan08da86a2009-08-21 17:18:03 +00005869** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5870** argument to this function.
5871**
5872** Such a file descriptor may exist if a database connection was closed
5873** but the associated file descriptor could not be closed because some
5874** other file descriptor open on the same file is holding a file-lock.
5875** Refer to comments in the unixClose() function and the lengthy comment
5876** describing "Posix Advisory Locking" at the start of this file for
5877** further details. Also, ticket #4018.
5878**
5879** If a suitable file descriptor is found, then it is returned. If no
5880** such file descriptor is located, -1 is returned.
5881*/
dane946c392009-08-22 11:39:46 +00005882static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5883 UnixUnusedFd *pUnused = 0;
5884
5885 /* Do not search for an unused file descriptor on vxworks. Not because
5886 ** vxworks would not benefit from the change (it might, we're not sure),
5887 ** but because no way to test it is currently available. It is better
5888 ** not to risk breaking vxworks support for the sake of such an obscure
5889 ** feature. */
5890#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005891 struct stat sStat; /* Results of stat() call */
5892
drhc68886b2017-08-18 16:09:52 +00005893 unixEnterMutex();
5894
dan08da86a2009-08-21 17:18:03 +00005895 /* A stat() call may fail for various reasons. If this happens, it is
5896 ** almost certain that an open() call on the same path will also fail.
5897 ** For this reason, if an error occurs in the stat() call here, it is
5898 ** ignored and -1 is returned. The caller will try to open a new file
5899 ** descriptor on the same path, fail, and return an error to SQLite.
5900 **
5901 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005902 ** not searching for a reusable file descriptor are not dire. */
drh095908e2018-08-13 20:46:18 +00005903 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005904 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005905
drh8af6c222010-05-14 12:43:01 +00005906 pInode = inodeList;
5907 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005908 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005909 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005910 }
drh8af6c222010-05-14 12:43:01 +00005911 if( pInode ){
dane946c392009-08-22 11:39:46 +00005912 UnixUnusedFd **pp;
drh095908e2018-08-13 20:46:18 +00005913 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5914 sqlite3_mutex_enter(pInode->pLockMutex);
drh55220a62019-08-06 20:55:06 +00005915 flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
drh8af6c222010-05-14 12:43:01 +00005916 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005917 pUnused = *pp;
5918 if( pUnused ){
5919 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005920 }
drh095908e2018-08-13 20:46:18 +00005921 sqlite3_mutex_leave(pInode->pLockMutex);
dan08da86a2009-08-21 17:18:03 +00005922 }
dan08da86a2009-08-21 17:18:03 +00005923 }
drhc68886b2017-08-18 16:09:52 +00005924 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005925#endif /* if !OS_VXWORKS */
5926 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005927}
danielk197717b90b52008-06-06 11:11:25 +00005928
5929/*
dan1bf4ca72016-08-11 18:05:47 +00005930** Find the mode, uid and gid of file zFile.
5931*/
5932static int getFileMode(
5933 const char *zFile, /* File name */
5934 mode_t *pMode, /* OUT: Permissions of zFile */
5935 uid_t *pUid, /* OUT: uid of zFile. */
5936 gid_t *pGid /* OUT: gid of zFile. */
5937){
5938 struct stat sStat; /* Output of stat() on database file */
5939 int rc = SQLITE_OK;
5940 if( 0==osStat(zFile, &sStat) ){
5941 *pMode = sStat.st_mode & 0777;
5942 *pUid = sStat.st_uid;
5943 *pGid = sStat.st_gid;
5944 }else{
5945 rc = SQLITE_IOERR_FSTAT;
5946 }
5947 return rc;
5948}
5949
5950/*
danddb0ac42010-07-14 14:48:58 +00005951** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005952** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005953** and a value suitable for passing as the third argument to open(2) is
5954** written to *pMode. If an IO error occurs, an SQLite error code is
5955** returned and the value of *pMode is not modified.
5956**
peter.d.reid60ec9142014-09-06 16:39:46 +00005957** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005958** an indication to robust_open() to create the file using
5959** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5960** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005961** this function queries the file-system for the permissions on the
5962** corresponding database file and sets *pMode to this value. Whenever
5963** possible, WAL and journal files are created using the same permissions
5964** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005965**
5966** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5967** original filename is unavailable. But 8_3_NAMES is only used for
5968** FAT filesystems and permissions do not matter there, so just use
drh1116b172019-09-25 10:36:31 +00005969** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
danddb0ac42010-07-14 14:48:58 +00005970*/
5971static int findCreateFileMode(
5972 const char *zPath, /* Path of file (possibly) being created */
5973 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005974 mode_t *pMode, /* OUT: Permissions to open file with */
5975 uid_t *pUid, /* OUT: uid to set on the file */
5976 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005977){
5978 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005979 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005980 *pUid = 0;
5981 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005982 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005983 char zDb[MAX_PATHNAME+1]; /* Database file path */
5984 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005985
dana0c989d2010-11-05 18:07:37 +00005986 /* zPath is a path to a WAL or journal file. The following block derives
5987 ** the path to the associated database file from zPath. This block handles
5988 ** the following naming conventions:
5989 **
5990 ** "<path to db>-journal"
5991 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005992 ** "<path to db>-journalNN"
5993 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005994 **
drhd337c5b2011-10-20 18:23:35 +00005995 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005996 ** used by the test_multiplex.c module.
5997 */
5998 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005999 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00006000 /* In normal operation, the journal file name will always contain
6001 ** a '-' character. However in 8+3 filename mode, or if a corrupt
drh067b92b2020-06-19 15:24:12 +00006002 ** rollback journal specifies a super-journal with a goofy name, then
dan629ec142017-09-14 20:41:17 +00006003 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00006004 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00006005 nDb--;
6006 }
danddb0ac42010-07-14 14:48:58 +00006007 memcpy(zDb, zPath, nDb);
6008 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00006009
dan1bf4ca72016-08-11 18:05:47 +00006010 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00006011 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
6012 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00006013 }else if( flags & SQLITE_OPEN_URI ){
6014 /* If this is a main database file and the file was opened using a URI
6015 ** filename, check for the "modeof" parameter. If present, interpret
6016 ** its value as a filename and try to copy the mode, uid and gid from
6017 ** that file. */
6018 const char *z = sqlite3_uri_parameter(zPath, "modeof");
6019 if( z ){
6020 rc = getFileMode(z, pMode, pUid, pGid);
6021 }
danddb0ac42010-07-14 14:48:58 +00006022 }
6023 return rc;
6024}
6025
6026/*
danielk1977ad94b582007-08-20 06:44:22 +00006027** Open the file zPath.
6028**
danielk1977b4b47412007-08-17 15:53:36 +00006029** Previously, the SQLite OS layer used three functions in place of this
6030** one:
6031**
6032** sqlite3OsOpenReadWrite();
6033** sqlite3OsOpenReadOnly();
6034** sqlite3OsOpenExclusive();
6035**
6036** These calls correspond to the following combinations of flags:
6037**
6038** ReadWrite() -> (READWRITE | CREATE)
6039** ReadOnly() -> (READONLY)
6040** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
6041**
6042** The old OpenExclusive() accepted a boolean argument - "delFlag". If
6043** true, the file was configured to be automatically deleted when the
6044** file handle closed. To achieve the same effect using this new
6045** interface, add the DELETEONCLOSE flag to those specified above for
6046** OpenExclusive().
6047*/
6048static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00006049 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
6050 const char *zPath, /* Pathname of file to be opened */
6051 sqlite3_file *pFile, /* The file descriptor to be filled in */
6052 int flags, /* Input flags to control the opening */
6053 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00006054){
dan08da86a2009-08-21 17:18:03 +00006055 unixFile *p = (unixFile *)pFile;
6056 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00006057 int openFlags = 0; /* Flags to pass to open() */
drhc398c652019-11-22 00:42:01 +00006058 int eType = flags&0x0FFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00006059 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00006060 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00006061 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00006062
6063 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
6064 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
6065 int isCreate = (flags & SQLITE_OPEN_CREATE);
6066 int isReadonly = (flags & SQLITE_OPEN_READONLY);
6067 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00006068#if SQLITE_ENABLE_LOCKING_STYLE
6069 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
6070#endif
drh3d4435b2011-08-26 20:55:50 +00006071#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6072 struct statfs fsInfo;
6073#endif
danielk1977b4b47412007-08-17 15:53:36 +00006074
drh067b92b2020-06-19 15:24:12 +00006075 /* If creating a super- or main-file journal, this function will open
danielk1977fee2d252007-08-18 10:59:19 +00006076 ** a file-descriptor on the directory too. The first time unixSync()
6077 ** is called the directory file descriptor will be fsync()ed and close()d.
6078 */
drha803a2c2017-12-13 20:02:29 +00006079 int isNewJrnl = (isCreate && (
drhccb21132020-06-19 11:34:57 +00006080 eType==SQLITE_OPEN_SUPER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00006081 || eType==SQLITE_OPEN_MAIN_JOURNAL
6082 || eType==SQLITE_OPEN_WAL
6083 ));
danielk1977fee2d252007-08-18 10:59:19 +00006084
danielk197717b90b52008-06-06 11:11:25 +00006085 /* If argument zPath is a NULL pointer, this function is required to open
6086 ** a temporary file. Use this buffer to store the file name in.
6087 */
drhc02a43a2012-01-10 23:18:38 +00006088 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00006089 const char *zName = zPath;
6090
danielk1977fee2d252007-08-18 10:59:19 +00006091 /* Check the following statements are true:
6092 **
6093 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
6094 ** (b) if CREATE is set, then READWRITE must also be set, and
6095 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00006096 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00006097 */
danielk1977b4b47412007-08-17 15:53:36 +00006098 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00006099 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00006100 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00006101 assert(isDelete==0 || isCreate);
6102
drh067b92b2020-06-19 15:24:12 +00006103 /* The main DB, main journal, WAL file and super-journal are never
danddb0ac42010-07-14 14:48:58 +00006104 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00006105 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
6106 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
drhccb21132020-06-19 11:34:57 +00006107 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006108 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00006109
danielk1977fee2d252007-08-18 10:59:19 +00006110 /* Assert that the upper layer has set one of the "file-type" flags. */
6111 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
6112 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
drhccb21132020-06-19 11:34:57 +00006113 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00006114 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00006115 );
6116
drhb00d8622014-01-01 15:18:36 +00006117 /* Detect a pid change and reset the PRNG. There is a race condition
6118 ** here such that two or more threads all trying to open databases at
6119 ** the same instant might all reset the PRNG. But multiple resets
6120 ** are harmless.
6121 */
drh5ac93652015-03-21 20:59:43 +00006122 if( randomnessPid!=osGetpid(0) ){
6123 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00006124 sqlite3_randomness(0,0);
6125 }
dan08da86a2009-08-21 17:18:03 +00006126 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00006127
dan08da86a2009-08-21 17:18:03 +00006128 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00006129 UnixUnusedFd *pUnused;
6130 pUnused = findReusableFd(zName, flags);
6131 if( pUnused ){
6132 fd = pUnused->fd;
6133 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006134 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00006135 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006136 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00006137 }
6138 }
drhc68886b2017-08-18 16:09:52 +00006139 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00006140
6141 /* Database filenames are double-zero terminated if they are not
6142 ** URIs with parameters. Hence, they can always be passed into
6143 ** sqlite3_uri_parameter(). */
6144 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
6145
dan08da86a2009-08-21 17:18:03 +00006146 }else if( !zName ){
6147 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00006148 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00006149 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00006150 if( rc!=SQLITE_OK ){
6151 return rc;
6152 }
6153 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00006154
6155 /* Generated temporary filenames are always double-zero terminated
6156 ** for use by sqlite3_uri_parameter(). */
6157 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00006158 }
6159
dan08da86a2009-08-21 17:18:03 +00006160 /* Determine the value of the flags parameter passed to POSIX function
6161 ** open(). These must be calculated even if open() is not called, as
6162 ** they may be stored as part of the file handle and used by the
6163 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00006164 if( isReadonly ) openFlags |= O_RDONLY;
6165 if( isReadWrite ) openFlags |= O_RDWR;
6166 if( isCreate ) openFlags |= O_CREAT;
6167 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
drhc398c652019-11-22 00:42:01 +00006168 openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
danielk1977b4b47412007-08-17 15:53:36 +00006169
danielk1977b4b47412007-08-17 15:53:36 +00006170 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00006171 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00006172 uid_t uid; /* Userid for the file */
6173 gid_t gid; /* Groupid for the file */
6174 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00006175 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006176 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00006177 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006178 return rc;
6179 }
drhad4f1e52011-03-04 15:43:57 +00006180 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00006181 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00006182 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00006183 if( fd<0 ){
6184 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6185 /* If unable to create a journal because the directory is not
6186 ** writable, change the error code to indicate that. */
6187 rc = SQLITE_READONLY_DIRECTORY;
6188 }else if( errno!=EISDIR && isReadWrite ){
6189 /* Failed to open the file for read/write access. Try read-only. */
6190 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6191 openFlags &= ~(O_RDWR|O_CREAT);
6192 flags |= SQLITE_OPEN_READONLY;
6193 openFlags |= O_RDONLY;
6194 isReadonly = 1;
6195 fd = robust_open(zName, openFlags, openMode);
6196 }
dan08da86a2009-08-21 17:18:03 +00006197 }
6198 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00006199 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6200 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00006201 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00006202 }
drhac7c3ac2012-02-11 19:23:48 +00006203
drh1116b172019-09-25 10:36:31 +00006204 /* The owner of the rollback journal or WAL file should always be the
6205 ** same as the owner of the database file. Try to ensure that this is
6206 ** the case. The chown() system call will be a no-op if the current
6207 ** process lacks root privileges, be we should at least try. Without
6208 ** this step, if a root process opens a database file, it can leave
6209 ** behinds a journal/WAL that is owned by root and hence make the
6210 ** database inaccessible to unprivileged processes.
6211 **
drhedf8a7b2019-09-25 11:49:36 +00006212 ** If openMode==0, then that means uid and gid are not set correctly
drh1116b172019-09-25 10:36:31 +00006213 ** (probably because SQLite is configured to use 8+3 filename mode) and
6214 ** in that case we do not want to attempt the chown().
drhac7c3ac2012-02-11 19:23:48 +00006215 */
drhedf8a7b2019-09-25 11:49:36 +00006216 if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
drh6226ca22015-11-24 15:06:28 +00006217 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00006218 }
danielk1977b4b47412007-08-17 15:53:36 +00006219 }
dan08da86a2009-08-21 17:18:03 +00006220 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00006221 if( pOutFlags ){
6222 *pOutFlags = flags;
6223 }
6224
drhc68886b2017-08-18 16:09:52 +00006225 if( p->pPreallocatedUnused ){
6226 p->pPreallocatedUnused->fd = fd;
drh55220a62019-08-06 20:55:06 +00006227 p->pPreallocatedUnused->flags =
6228 flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
dane946c392009-08-22 11:39:46 +00006229 }
6230
danielk1977b4b47412007-08-17 15:53:36 +00006231 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00006232#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006233 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00006234#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6235 zPath = sqlite3_mprintf("%s", zName);
6236 if( zPath==0 ){
6237 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00006238 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00006239 }
chw97185482008-11-17 08:05:31 +00006240#else
drh036ac7f2011-08-08 23:18:05 +00006241 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00006242#endif
danielk1977b4b47412007-08-17 15:53:36 +00006243 }
drh41022642008-11-21 00:24:42 +00006244#if SQLITE_ENABLE_LOCKING_STYLE
6245 else{
dan08da86a2009-08-21 17:18:03 +00006246 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00006247 }
6248#endif
drh7ed97b92010-01-20 13:07:21 +00006249
6250#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00006251 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00006252 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00006253 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006254 return SQLITE_IOERR_ACCESS;
6255 }
6256 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6257 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6258 }
drh4bf66fd2015-02-19 02:43:02 +00006259 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6260 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6261 }
drh7ed97b92010-01-20 13:07:21 +00006262#endif
drhc02a43a2012-01-10 23:18:38 +00006263
6264 /* Set up appropriate ctrlFlags */
6265 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6266 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00006267 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00006268 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00006269 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00006270 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6271
drh7ed97b92010-01-20 13:07:21 +00006272#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00006273#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00006274 isAutoProxy = 1;
6275#endif
6276 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00006277 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6278 int useProxy = 0;
6279
dan08da86a2009-08-21 17:18:03 +00006280 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6281 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00006282 if( envforce!=NULL ){
6283 useProxy = atoi(envforce)>0;
6284 }else{
aswiftaebf4132008-11-21 00:10:35 +00006285 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6286 }
6287 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006288 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006289 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006290 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006291 if( rc!=SQLITE_OK ){
6292 /* Use unixClose to clean up the resources added in fillInUnixFile
6293 ** and clear all the structure's references. Specifically,
6294 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6295 */
6296 unixClose(pFile);
6297 return rc;
6298 }
aswiftaebf4132008-11-21 00:10:35 +00006299 }
dane946c392009-08-22 11:39:46 +00006300 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006301 }
6302 }
6303#endif
6304
dan3ed0f1c2017-09-14 21:12:07 +00006305 assert( zPath==0 || zPath[0]=='/'
drhccb21132020-06-19 11:34:57 +00006306 || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
dan3ed0f1c2017-09-14 21:12:07 +00006307 );
drhc02a43a2012-01-10 23:18:38 +00006308 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6309
dane946c392009-08-22 11:39:46 +00006310open_finished:
6311 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006312 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006313 }
6314 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006315}
6316
dane946c392009-08-22 11:39:46 +00006317
danielk1977b4b47412007-08-17 15:53:36 +00006318/*
danielk1977fee2d252007-08-18 10:59:19 +00006319** Delete the file at zPath. If the dirSync argument is true, fsync()
6320** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006321*/
drh6b9d6dd2008-12-03 19:34:47 +00006322static int unixDelete(
6323 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6324 const char *zPath, /* Name of file to be deleted */
6325 int dirSync /* If true, fsync() directory after deleting file */
6326){
danielk1977fee2d252007-08-18 10:59:19 +00006327 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006328 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006329 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006330 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006331 if( errno==ENOENT
6332#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006333 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006334#endif
6335 ){
dan9fc5b4a2012-11-09 20:17:26 +00006336 rc = SQLITE_IOERR_DELETE_NOENT;
6337 }else{
drhb4308162012-11-09 21:40:02 +00006338 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006339 }
drhb4308162012-11-09 21:40:02 +00006340 return rc;
drh5d4feff2010-07-14 01:45:22 +00006341 }
danielk1977d39fa702008-10-16 13:27:40 +00006342#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006343 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006344 int fd;
drh90315a22011-08-10 01:52:12 +00006345 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006346 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006347 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006348 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006349 }
drh0e9365c2011-03-02 02:08:13 +00006350 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006351 }else{
6352 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006353 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006354 }
6355 }
danielk1977d138dd82008-10-15 16:02:48 +00006356#endif
danielk1977fee2d252007-08-18 10:59:19 +00006357 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006358}
6359
danielk197790949c22007-08-17 16:50:38 +00006360/*
mistachkin48864df2013-03-21 21:20:32 +00006361** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006362** test performed depends on the value of flags:
6363**
6364** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6365** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6366** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6367**
6368** Otherwise return 0.
6369*/
danielk1977861f7452008-06-05 11:39:11 +00006370static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006371 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6372 const char *zPath, /* Path of the file to examine */
6373 int flags, /* What do we want to learn about the zPath file? */
6374 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006375){
danielk1977397d65f2008-11-19 11:35:39 +00006376 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006377 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006378 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006379
drhc398c652019-11-22 00:42:01 +00006380 /* The spec says there are three possible values for flags. But only
6381 ** two of them are actually used */
6382 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
drhd260b5b2015-11-25 18:03:33 +00006383
6384 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006385 struct stat buf;
drh96e8eeb2019-12-26 00:56:50 +00006386 *pResOut = 0==osStat(zPath, &buf) &&
drh09bee572019-12-27 13:30:46 +00006387 (!S_ISREG(buf.st_mode) || buf.st_size>0);
drh0933aad2019-11-18 17:46:38 +00006388 }else{
drhc398c652019-11-22 00:42:01 +00006389 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006390 }
danielk1977861f7452008-06-05 11:39:11 +00006391 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006392}
6393
danielk1977b4b47412007-08-17 15:53:36 +00006394/*
drh7f42dcd2020-11-16 18:45:21 +00006395** If the last component of the pathname in z[0]..z[j-1] is something
6396** other than ".." then back it out and return true. If the last
6397** component is empty or if it is ".." then return false.
6398*/
6399static int unixBackupDir(const char *z, int *pJ){
6400 int j = *pJ;
6401 int i;
6402 if( j<=0 ) return 0;
drh8e7c82c2021-03-18 13:55:25 +00006403 for(i=j-1; i>0 && z[i-1]!='/'; i--){}
6404 if( i==0 ) return 0;
drh7f42dcd2020-11-16 18:45:21 +00006405 if( z[i]=='.' && i==j-2 && z[i+1]=='.' ) return 0;
6406 *pJ = i-1;
6407 return 1;
6408}
6409
6410/*
6411** Convert a relative pathname into a full pathname. Also
6412** simplify the pathname as follows:
danielk1977b4b47412007-08-17 15:53:36 +00006413**
drh7f42dcd2020-11-16 18:45:21 +00006414** Remove all instances of /./
6415** Remove all isntances of /X/../ for any X
danielk1977b4b47412007-08-17 15:53:36 +00006416*/
dane88ec182016-01-25 17:04:48 +00006417static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006418 const char *zPath, /* Input path */
6419 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006420 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006421){
dancaf6b152016-01-25 18:05:49 +00006422 int nPath = sqlite3Strlen30(zPath);
6423 int iOff = 0;
drh7f42dcd2020-11-16 18:45:21 +00006424 int i, j;
dancaf6b152016-01-25 18:05:49 +00006425 if( zPath[0]!='/' ){
6426 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006427 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006428 }
dancaf6b152016-01-25 18:05:49 +00006429 iOff = sqlite3Strlen30(zOut);
6430 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006431 }
dan23496702016-01-26 13:56:42 +00006432 if( (iOff+nPath+1)>nOut ){
6433 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6434 ** even if it returns an error. */
6435 zOut[iOff] = '\0';
6436 return SQLITE_CANTOPEN_BKPT;
6437 }
dancaf6b152016-01-25 18:05:49 +00006438 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
drh7f42dcd2020-11-16 18:45:21 +00006439
6440 /* Remove duplicate '/' characters. Except, two // at the beginning
6441 ** of a pathname is allowed since this is important on windows. */
6442 for(i=j=1; zOut[i]; i++){
6443 zOut[j++] = zOut[i];
6444 while( zOut[i]=='/' && zOut[i+1]=='/' ) i++;
6445 }
6446 zOut[j] = 0;
6447
drhd46beb02020-11-23 17:36:06 +00006448 assert( zOut[0]=='/' );
drh7f42dcd2020-11-16 18:45:21 +00006449 for(i=j=0; zOut[i]; i++){
6450 if( zOut[i]=='/' ){
6451 /* Skip over internal "/." directory components */
6452 if( zOut[i+1]=='.' && zOut[i+2]=='/' ){
6453 i += 1;
6454 continue;
6455 }
6456
6457 /* If this is a "/.." directory component then back out the
6458 ** previous term of the directory if it is something other than "..".
6459 */
6460 if( zOut[i+1]=='.'
6461 && zOut[i+2]=='.'
6462 && zOut[i+3]=='/'
6463 && unixBackupDir(zOut, &j)
6464 ){
6465 i += 2;
6466 continue;
6467 }
6468 }
drhd46beb02020-11-23 17:36:06 +00006469 if( ALWAYS(j>=0) ) zOut[j] = zOut[i];
drh7f42dcd2020-11-16 18:45:21 +00006470 j++;
6471 }
drhd46beb02020-11-23 17:36:06 +00006472 if( NEVER(j==0) ) zOut[j++] = '/';
drh7f42dcd2020-11-16 18:45:21 +00006473 zOut[j] = 0;
danielk1977b4b47412007-08-17 15:53:36 +00006474 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006475}
6476
dane88ec182016-01-25 17:04:48 +00006477/*
6478** Turn a relative pathname into a full pathname. The relative path
6479** is stored as a nul-terminated string in the buffer pointed to by
6480** zPath.
6481**
6482** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6483** (in this case, MAX_PATHNAME bytes). The full-path is written to
6484** this buffer before returning.
6485*/
6486static int unixFullPathname(
6487 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6488 const char *zPath, /* Possibly relative input path */
6489 int nOut, /* Size of output buffer in bytes */
6490 char *zOut /* Output buffer */
6491){
danaf1b36b2016-01-25 18:43:05 +00006492#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006493 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006494#else
6495 int rc = SQLITE_OK;
6496 int nByte;
drhc398c652019-11-22 00:42:01 +00006497 int nLink = 0; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006498 const char *zIn = zPath; /* Input path for each iteration of loop */
6499 char *zDel = 0;
6500
6501 assert( pVfs->mxPathname==MAX_PATHNAME );
6502 UNUSED_PARAMETER(pVfs);
6503
6504 /* It's odd to simulate an io-error here, but really this is just
6505 ** using the io-error infrastructure to test that SQLite handles this
6506 ** function failing. This function could fail if, for example, the
6507 ** current working directory has been unlinked.
6508 */
6509 SimulateIOError( return SQLITE_ERROR );
6510
6511 do {
6512
dancaf6b152016-01-25 18:05:49 +00006513 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6514 ** link, or false otherwise. */
6515 int bLink = 0;
6516 struct stat buf;
6517 if( osLstat(zIn, &buf)!=0 ){
6518 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006519 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006520 }
dane88ec182016-01-25 17:04:48 +00006521 }else{
dancaf6b152016-01-25 18:05:49 +00006522 bLink = S_ISLNK(buf.st_mode);
6523 }
6524
6525 if( bLink ){
drhc398c652019-11-22 00:42:01 +00006526 nLink++;
dane88ec182016-01-25 17:04:48 +00006527 if( zDel==0 ){
6528 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006529 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
drhc398c652019-11-22 00:42:01 +00006530 }else if( nLink>=SQLITE_MAX_SYMLINKS ){
dancaf6b152016-01-25 18:05:49 +00006531 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006532 }
dancaf6b152016-01-25 18:05:49 +00006533
6534 if( rc==SQLITE_OK ){
6535 nByte = osReadlink(zIn, zDel, nOut-1);
6536 if( nByte<0 ){
6537 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006538 }else{
6539 if( zDel[0]!='/' ){
6540 int n;
6541 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6542 if( nByte+n+1>nOut ){
6543 rc = SQLITE_CANTOPEN_BKPT;
6544 }else{
6545 memmove(&zDel[n], zDel, nByte+1);
6546 memcpy(zDel, zIn, n);
6547 nByte += n;
6548 }
dancaf6b152016-01-25 18:05:49 +00006549 }
6550 zDel[nByte] = '\0';
6551 }
6552 }
6553
6554 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006555 }
6556
dan23496702016-01-26 13:56:42 +00006557 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6558 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006559 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006560 }
dancaf6b152016-01-25 18:05:49 +00006561 if( bLink==0 ) break;
6562 zIn = zOut;
6563 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006564
6565 sqlite3_free(zDel);
drhc398c652019-11-22 00:42:01 +00006566 if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK;
dane88ec182016-01-25 17:04:48 +00006567 return rc;
danaf1b36b2016-01-25 18:43:05 +00006568#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006569}
6570
drh0ccebe72005-06-07 22:22:50 +00006571
drh761df872006-12-21 01:29:22 +00006572#ifndef SQLITE_OMIT_LOAD_EXTENSION
6573/*
6574** Interfaces for opening a shared library, finding entry points
6575** within the shared library, and closing the shared library.
6576*/
6577#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006578static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6579 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006580 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6581}
danielk197795c8a542007-09-01 06:51:27 +00006582
6583/*
6584** SQLite calls this function immediately after a call to unixDlSym() or
6585** unixDlOpen() fails (returns a null pointer). If a more detailed error
6586** message is available, it is written to zBufOut. If no error message
6587** is available, zBufOut is left unmodified and SQLite uses a default
6588** error message.
6589*/
danielk1977397d65f2008-11-19 11:35:39 +00006590static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006591 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006592 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006593 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006594 zErr = dlerror();
6595 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006596 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006597 }
drh6c7d5c52008-11-21 20:32:33 +00006598 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006599}
drh1875f7a2008-12-08 18:19:17 +00006600static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6601 /*
6602 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6603 ** cast into a pointer to a function. And yet the library dlsym() routine
6604 ** returns a void* which is really a pointer to a function. So how do we
6605 ** use dlsym() with -pedantic-errors?
6606 **
6607 ** Variable x below is defined to be a pointer to a function taking
6608 ** parameters void* and const char* and returning a pointer to a function.
6609 ** We initialize x by assigning it a pointer to the dlsym() function.
6610 ** (That assignment requires a cast.) Then we call the function that
6611 ** x points to.
6612 **
6613 ** This work-around is unlikely to work correctly on any system where
6614 ** you really cannot cast a function pointer into void*. But then, on the
6615 ** other hand, dlsym() will not work on such a system either, so we have
6616 ** not really lost anything.
6617 */
6618 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006619 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006620 x = (void(*(*)(void*,const char*))(void))dlsym;
6621 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006622}
danielk1977397d65f2008-11-19 11:35:39 +00006623static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6624 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006625 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006626}
danielk1977b4b47412007-08-17 15:53:36 +00006627#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6628 #define unixDlOpen 0
6629 #define unixDlError 0
6630 #define unixDlSym 0
6631 #define unixDlClose 0
6632#endif
6633
6634/*
danielk197790949c22007-08-17 16:50:38 +00006635** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006636*/
danielk1977397d65f2008-11-19 11:35:39 +00006637static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6638 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006639 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006640
drhbbd42a62004-05-22 17:41:58 +00006641 /* We have to initialize zBuf to prevent valgrind from reporting
6642 ** errors. The reports issued by valgrind are incorrect - we would
6643 ** prefer that the randomness be increased by making use of the
6644 ** uninitialized space in zBuf - but valgrind errors tend to worry
6645 ** some users. Rather than argue, it seems easier just to initialize
6646 ** the whole array and silence valgrind, even if that means less randomness
6647 ** in the random seed.
6648 **
6649 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006650 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006651 ** tests repeatable.
6652 */
danielk1977b4b47412007-08-17 15:53:36 +00006653 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006654 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006655#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006656 {
drhb00d8622014-01-01 15:18:36 +00006657 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006658 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006659 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006660 time_t t;
6661 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006662 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006663 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6664 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6665 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006666 }else{
drhc18b4042012-02-10 03:10:27 +00006667 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006668 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006669 }
drhbbd42a62004-05-22 17:41:58 +00006670 }
6671#endif
drh72cbd072008-10-14 17:58:38 +00006672 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006673}
6674
danielk1977b4b47412007-08-17 15:53:36 +00006675
drhbbd42a62004-05-22 17:41:58 +00006676/*
6677** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006678** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006679** The return value is the number of microseconds of sleep actually
6680** requested from the underlying operating system, a number which
6681** might be greater than or equal to the argument, but not less
6682** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006683*/
danielk1977397d65f2008-11-19 11:35:39 +00006684static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006685#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006686 struct timespec sp;
6687
6688 sp.tv_sec = microseconds / 1000000;
6689 sp.tv_nsec = (microseconds % 1000000) * 1000;
6690 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006691 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006692 return microseconds;
6693#elif defined(HAVE_USLEEP) && HAVE_USLEEP
drhddcfe922020-09-15 12:29:35 +00006694 if( microseconds>=1000000 ) sleep(microseconds/1000000);
6695 if( microseconds%1000000 ) usleep(microseconds%1000000);
drhd43fe202009-03-01 22:29:20 +00006696 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006697 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006698#else
danielk1977b4b47412007-08-17 15:53:36 +00006699 int seconds = (microseconds+999999)/1000000;
6700 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006701 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006702 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006703#endif
drh88f474a2006-01-02 20:00:12 +00006704}
6705
6706/*
drh6b9d6dd2008-12-03 19:34:47 +00006707** The following variable, if set to a non-zero value, is interpreted as
6708** the number of seconds since 1970 and is used to set the result of
6709** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006710*/
6711#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006712int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006713#endif
6714
6715/*
drhb7e8ea22010-05-03 14:32:30 +00006716** Find the current time (in Universal Coordinated Time). Write into *piNow
6717** the current time and date as a Julian Day number times 86_400_000. In
6718** other words, write into *piNow the number of milliseconds since the Julian
6719** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6720** proleptic Gregorian calendar.
6721**
drh31702252011-10-12 23:13:43 +00006722** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6723** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006724*/
6725static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6726 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006727 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006728#if defined(NO_GETTOD)
6729 time_t t;
6730 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006731 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006732#elif OS_VXWORKS
6733 struct timespec sNow;
6734 clock_gettime(CLOCK_REALTIME, &sNow);
6735 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6736#else
6737 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006738 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6739 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006740#endif
6741
6742#ifdef SQLITE_TEST
6743 if( sqlite3_current_time ){
6744 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6745 }
6746#endif
6747 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006748 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006749}
6750
drhc3dfa5e2016-01-22 19:44:03 +00006751#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006752/*
drhbbd42a62004-05-22 17:41:58 +00006753** Find the current time (in Universal Coordinated Time). Write the
6754** current time and date as a Julian Day number into *prNow and
6755** return 0. Return 1 if the time and date cannot be found.
6756*/
danielk1977397d65f2008-11-19 11:35:39 +00006757static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006758 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006759 int rc;
drhff828942010-06-26 21:34:06 +00006760 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006761 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006762 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006763 return rc;
drhbbd42a62004-05-22 17:41:58 +00006764}
drh5337dac2015-11-25 15:15:03 +00006765#else
6766# define unixCurrentTime 0
6767#endif
danielk1977b4b47412007-08-17 15:53:36 +00006768
drh6b9d6dd2008-12-03 19:34:47 +00006769/*
drh1b9f2142016-03-17 16:01:23 +00006770** The xGetLastError() method is designed to return a better
6771** low-level error message when operating-system problems come up
6772** during SQLite operation. Only the integer return code is currently
6773** used.
drh6b9d6dd2008-12-03 19:34:47 +00006774*/
danielk1977397d65f2008-11-19 11:35:39 +00006775static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6776 UNUSED_PARAMETER(NotUsed);
6777 UNUSED_PARAMETER(NotUsed2);
6778 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006779 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006780}
6781
drhf2424c52010-04-26 00:04:55 +00006782
6783/*
drh734c9862008-11-28 15:37:20 +00006784************************ End of sqlite3_vfs methods ***************************
6785******************************************************************************/
6786
drh715ff302008-12-03 22:32:44 +00006787/******************************************************************************
6788************************** Begin Proxy Locking ********************************
6789**
6790** Proxy locking is a "uber-locking-method" in this sense: It uses the
6791** other locking methods on secondary lock files. Proxy locking is a
6792** meta-layer over top of the primitive locking implemented above. For
6793** this reason, the division that implements of proxy locking is deferred
6794** until late in the file (here) after all of the other I/O methods have
6795** been defined - so that the primitive locking methods are available
6796** as services to help with the implementation of proxy locking.
6797**
6798****
6799**
6800** The default locking schemes in SQLite use byte-range locks on the
6801** database file to coordinate safe, concurrent access by multiple readers
6802** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6803** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6804** as POSIX read & write locks over fixed set of locations (via fsctl),
6805** on AFP and SMB only exclusive byte-range locks are available via fsctl
6806** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6807** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6808** address in the shared range is taken for a SHARED lock, the entire
6809** shared range is taken for an EXCLUSIVE lock):
6810**
drhf2f105d2012-08-20 15:53:54 +00006811** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006812** RESERVED_BYTE 0x40000001
6813** SHARED_RANGE 0x40000002 -> 0x40000200
6814**
6815** This works well on the local file system, but shows a nearly 100x
6816** slowdown in read performance on AFP because the AFP client disables
6817** the read cache when byte-range locks are present. Enabling the read
6818** cache exposes a cache coherency problem that is present on all OS X
6819** supported network file systems. NFS and AFP both observe the
6820** close-to-open semantics for ensuring cache coherency
6821** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6822** address the requirements for concurrent database access by multiple
6823** readers and writers
6824** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6825**
6826** To address the performance and cache coherency issues, proxy file locking
6827** changes the way database access is controlled by limiting access to a
6828** single host at a time and moving file locks off of the database file
6829** and onto a proxy file on the local file system.
6830**
6831**
6832** Using proxy locks
6833** -----------------
6834**
6835** C APIs
6836**
drh4bf66fd2015-02-19 02:43:02 +00006837** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006838** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006839** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6840** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006841**
6842**
6843** SQL pragmas
6844**
6845** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6846** PRAGMA [database.]lock_proxy_file
6847**
6848** Specifying ":auto:" means that if there is a conch file with a matching
6849** host ID in it, the proxy path in the conch file will be used, otherwise
6850** a proxy path based on the user's temp dir
6851** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6852** actual proxy file name is generated from the name and path of the
6853** database file. For example:
6854**
6855** For database path "/Users/me/foo.db"
6856** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6857**
6858** Once a lock proxy is configured for a database connection, it can not
6859** be removed, however it may be switched to a different proxy path via
6860** the above APIs (assuming the conch file is not being held by another
6861** connection or process).
6862**
6863**
6864** How proxy locking works
6865** -----------------------
6866**
6867** Proxy file locking relies primarily on two new supporting files:
6868**
6869** * conch file to limit access to the database file to a single host
6870** at a time
6871**
6872** * proxy file to act as a proxy for the advisory locks normally
6873** taken on the database
6874**
6875** The conch file - to use a proxy file, sqlite must first "hold the conch"
6876** by taking an sqlite-style shared lock on the conch file, reading the
6877** contents and comparing the host's unique host ID (see below) and lock
6878** proxy path against the values stored in the conch. The conch file is
6879** stored in the same directory as the database file and the file name
6880** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006881** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006882** host ID and/or proxy path, then the lock is escalated to an exclusive
6883** lock and the conch file contents is updated with the host ID and proxy
6884** path and the lock is downgraded to a shared lock again. If the conch
6885** is held by another process (with a shared lock), the exclusive lock
6886** will fail and SQLITE_BUSY is returned.
6887**
6888** The proxy file - a single-byte file used for all advisory file locks
6889** normally taken on the database file. This allows for safe sharing
6890** of the database file for multiple readers and writers on the same
6891** host (the conch ensures that they all use the same local lock file).
6892**
drh715ff302008-12-03 22:32:44 +00006893** Requesting the lock proxy does not immediately take the conch, it is
6894** only taken when the first request to lock database file is made.
6895** This matches the semantics of the traditional locking behavior, where
6896** opening a connection to a database file does not take a lock on it.
6897** The shared lock and an open file descriptor are maintained until
6898** the connection to the database is closed.
6899**
6900** The proxy file and the lock file are never deleted so they only need
6901** to be created the first time they are used.
6902**
6903** Configuration options
6904** ---------------------
6905**
6906** SQLITE_PREFER_PROXY_LOCKING
6907**
6908** Database files accessed on non-local file systems are
6909** automatically configured for proxy locking, lock files are
6910** named automatically using the same logic as
6911** PRAGMA lock_proxy_file=":auto:"
6912**
6913** SQLITE_PROXY_DEBUG
6914**
6915** Enables the logging of error messages during host id file
6916** retrieval and creation
6917**
drh715ff302008-12-03 22:32:44 +00006918** LOCKPROXYDIR
6919**
6920** Overrides the default directory used for lock proxy files that
6921** are named automatically via the ":auto:" setting
6922**
6923** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6924**
6925** Permissions to use when creating a directory for storing the
6926** lock proxy files, only used when LOCKPROXYDIR is not set.
6927**
6928**
6929** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6930** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6931** force proxy locking to be used for every database file opened, and 0
6932** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006933** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006934** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6935*/
6936
6937/*
6938** Proxy locking is only available on MacOSX
6939*/
drhd2cb50b2009-01-09 21:41:17 +00006940#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006941
drh715ff302008-12-03 22:32:44 +00006942/*
6943** The proxyLockingContext has the path and file structures for the remote
6944** and local proxy files in it
6945*/
6946typedef struct proxyLockingContext proxyLockingContext;
6947struct proxyLockingContext {
6948 unixFile *conchFile; /* Open conch file */
6949 char *conchFilePath; /* Name of the conch file */
6950 unixFile *lockProxy; /* Open proxy lock file */
6951 char *lockProxyPath; /* Name of the proxy lock file */
6952 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006953 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006954 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006955 void *oldLockingContext; /* Original lockingcontext to restore on close */
6956 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6957};
6958
drh7ed97b92010-01-20 13:07:21 +00006959/*
6960** The proxy lock file path for the database at dbPath is written into lPath,
6961** which must point to valid, writable memory large enough for a maxLen length
6962** file path.
drh715ff302008-12-03 22:32:44 +00006963*/
drh715ff302008-12-03 22:32:44 +00006964static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6965 int len;
6966 int dbLen;
6967 int i;
6968
6969#ifdef LOCKPROXYDIR
6970 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6971#else
6972# ifdef _CS_DARWIN_USER_TEMP_DIR
6973 {
drh7ed97b92010-01-20 13:07:21 +00006974 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006975 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006976 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006977 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006978 }
drh7ed97b92010-01-20 13:07:21 +00006979 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006980 }
6981# else
6982 len = strlcpy(lPath, "/tmp/", maxLen);
6983# endif
6984#endif
6985
6986 if( lPath[len-1]!='/' ){
6987 len = strlcat(lPath, "/", maxLen);
6988 }
6989
6990 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006991 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006992 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006993 char c = dbPath[i];
6994 lPath[i+len] = (c=='/')?'_':c;
6995 }
6996 lPath[i+len]='\0';
6997 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006998 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006999 return SQLITE_OK;
7000}
7001
drh7ed97b92010-01-20 13:07:21 +00007002/*
7003 ** Creates the lock file and any missing directories in lockPath
7004 */
7005static int proxyCreateLockPath(const char *lockPath){
7006 int i, len;
7007 char buf[MAXPATHLEN];
7008 int start = 0;
7009
7010 assert(lockPath!=NULL);
7011 /* try to create all the intermediate directories */
7012 len = (int)strlen(lockPath);
7013 buf[0] = lockPath[0];
7014 for( i=1; i<len; i++ ){
7015 if( lockPath[i] == '/' && (i - start > 0) ){
7016 /* only mkdir if leaf dir != "." or "/" or ".." */
7017 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
7018 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
7019 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00007020 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00007021 int err=errno;
7022 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00007023 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00007024 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00007025 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007026 return err;
7027 }
7028 }
7029 }
7030 start=i+1;
7031 }
7032 buf[i] = lockPath[i];
7033 }
drh62aaa6c2015-11-21 17:27:42 +00007034 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007035 return 0;
7036}
7037
drh715ff302008-12-03 22:32:44 +00007038/*
7039** Create a new VFS file descriptor (stored in memory obtained from
7040** sqlite3_malloc) and open the file named "path" in the file descriptor.
7041**
7042** The caller is responsible not only for closing the file descriptor
7043** but also for freeing the memory associated with the file descriptor.
7044*/
drh7ed97b92010-01-20 13:07:21 +00007045static int proxyCreateUnixFile(
7046 const char *path, /* path for the new unixFile */
7047 unixFile **ppFile, /* unixFile created and returned by ref */
7048 int islockfile /* if non zero missing dirs will be created */
7049) {
7050 int fd = -1;
drh715ff302008-12-03 22:32:44 +00007051 unixFile *pNew;
7052 int rc = SQLITE_OK;
drhc398c652019-11-22 00:42:01 +00007053 int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
drh715ff302008-12-03 22:32:44 +00007054 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00007055 int terrno = 0;
7056 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00007057
drh7ed97b92010-01-20 13:07:21 +00007058 /* 1. first try to open/create the file
7059 ** 2. if that fails, and this is a lock file (not-conch), try creating
7060 ** the parent directories and then try again.
7061 ** 3. if that fails, try to open the file read-only
7062 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
7063 */
7064 pUnused = findReusableFd(path, openFlags);
7065 if( pUnused ){
7066 fd = pUnused->fd;
7067 }else{
drhf3cdcdc2015-04-29 16:50:28 +00007068 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00007069 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00007070 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007071 }
7072 }
7073 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00007074 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00007075 terrno = errno;
7076 if( fd<0 && errno==ENOENT && islockfile ){
7077 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00007078 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00007079 }
7080 }
7081 }
7082 if( fd<0 ){
drhc398c652019-11-22 00:42:01 +00007083 openFlags = O_RDONLY | O_NOFOLLOW;
drh8c815d12012-02-13 20:16:37 +00007084 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00007085 terrno = errno;
7086 }
7087 if( fd<0 ){
7088 if( islockfile ){
7089 return SQLITE_BUSY;
7090 }
7091 switch (terrno) {
7092 case EACCES:
7093 return SQLITE_PERM;
7094 case EIO:
7095 return SQLITE_IOERR_LOCK; /* even though it is the conch */
7096 default:
drh9978c972010-02-23 17:36:32 +00007097 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007098 }
7099 }
7100
drhf3cdcdc2015-04-29 16:50:28 +00007101 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00007102 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007103 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007104 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00007105 }
7106 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00007107 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00007108 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00007109 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00007110 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00007111 pUnused->fd = fd;
7112 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00007113 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00007114
drhc02a43a2012-01-10 23:18:38 +00007115 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00007116 if( rc==SQLITE_OK ){
7117 *ppFile = pNew;
7118 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00007119 }
drh7ed97b92010-01-20 13:07:21 +00007120end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00007121 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007122 sqlite3_free(pNew);
7123 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00007124 return rc;
7125}
7126
drh7ed97b92010-01-20 13:07:21 +00007127#ifdef SQLITE_TEST
7128/* simulate multiple hosts by creating unique hostid file paths */
7129int sqlite3_hostid_num = 0;
7130#endif
7131
7132#define PROXY_HOSTIDLEN 16 /* conch file host id length */
7133
drhe4079e12019-09-27 16:33:27 +00007134#if HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00007135/* Not always defined in the headers as it ought to be */
7136extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00007137#endif
drh0ab216a2010-07-02 17:10:40 +00007138
drh7ed97b92010-01-20 13:07:21 +00007139/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
7140** bytes of writable memory.
7141*/
7142static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00007143 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
7144 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe4079e12019-09-27 16:33:27 +00007145#if HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00007146 {
drh4bf66fd2015-02-19 02:43:02 +00007147 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00007148 if( gethostuuid(pHostID, &timeout) ){
7149 int err = errno;
7150 if( pError ){
7151 *pError = err;
7152 }
7153 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00007154 }
drh7ed97b92010-01-20 13:07:21 +00007155 }
drh3d4435b2011-08-26 20:55:50 +00007156#else
7157 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00007158#endif
drh7ed97b92010-01-20 13:07:21 +00007159#ifdef SQLITE_TEST
7160 /* simulate multiple hosts by creating unique hostid file paths */
7161 if( sqlite3_hostid_num != 0){
7162 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
7163 }
7164#endif
7165
7166 return SQLITE_OK;
7167}
7168
7169/* The conch file contains the header, host id and lock file path
7170 */
7171#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7172#define PROXY_HEADERLEN 1 /* conch file header length */
7173#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7174#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7175
7176/*
7177** Takes an open conch file, copies the contents to a new path and then moves
7178** it back. The newly created file's file descriptor is assigned to the
7179** conch file structure and finally the original conch file descriptor is
7180** closed. Returns zero if successful.
7181*/
7182static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
7183 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7184 unixFile *conchFile = pCtx->conchFile;
7185 char tPath[MAXPATHLEN];
7186 char buf[PROXY_MAXCONCHLEN];
7187 char *cPath = pCtx->conchFilePath;
7188 size_t readLen = 0;
7189 size_t pathLen = 0;
7190 char errmsg[64] = "";
7191 int fd = -1;
7192 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00007193 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00007194
7195 /* create a new path by replace the trailing '-conch' with '-break' */
7196 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
7197 if( pathLen>MAXPATHLEN || pathLen<6 ||
7198 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00007199 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00007200 goto end_breaklock;
7201 }
7202 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00007203 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007204 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00007205 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00007206 goto end_breaklock;
7207 }
7208 /* write it out to the temporary break file */
drhc398c652019-11-22 00:42:01 +00007209 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
drh7ed97b92010-01-20 13:07:21 +00007210 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00007211 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007212 goto end_breaklock;
7213 }
drhe562be52011-03-02 18:01:10 +00007214 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00007215 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007216 goto end_breaklock;
7217 }
7218 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00007219 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007220 goto end_breaklock;
7221 }
7222 rc = 0;
7223 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00007224 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007225 conchFile->h = fd;
7226 conchFile->openFlags = O_RDWR | O_CREAT;
7227
7228end_breaklock:
7229 if( rc ){
7230 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00007231 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00007232 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007233 }
7234 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7235 }
7236 return rc;
7237}
7238
7239/* Take the requested lock on the conch file and break a stale lock if the
7240** host id matches.
7241*/
7242static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7243 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7244 unixFile *conchFile = pCtx->conchFile;
7245 int rc = SQLITE_OK;
7246 int nTries = 0;
7247 struct timespec conchModTime;
7248
drh3d4435b2011-08-26 20:55:50 +00007249 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00007250 do {
7251 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7252 nTries ++;
7253 if( rc==SQLITE_BUSY ){
7254 /* If the lock failed (busy):
7255 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7256 * 2nd try: fail if the mod time changed or host id is different, wait
7257 * 10 sec and try again
7258 * 3rd try: break the lock unless the mod time has changed.
7259 */
7260 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007261 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00007262 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007263 return SQLITE_IOERR_LOCK;
7264 }
7265
7266 if( nTries==1 ){
7267 conchModTime = buf.st_mtimespec;
drhddcfe922020-09-15 12:29:35 +00007268 unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/
drh7ed97b92010-01-20 13:07:21 +00007269 continue;
7270 }
7271
7272 assert( nTries>1 );
7273 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7274 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7275 return SQLITE_BUSY;
7276 }
7277
7278 if( nTries==2 ){
7279 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00007280 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007281 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00007282 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007283 return SQLITE_IOERR_LOCK;
7284 }
7285 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7286 /* don't break the lock if the host id doesn't match */
7287 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7288 return SQLITE_BUSY;
7289 }
7290 }else{
7291 /* don't break the lock on short read or a version mismatch */
7292 return SQLITE_BUSY;
7293 }
drhddcfe922020-09-15 12:29:35 +00007294 unixSleep(0,10000000); /* wait 10 sec and try the lock again */
drh7ed97b92010-01-20 13:07:21 +00007295 continue;
7296 }
7297
7298 assert( nTries==3 );
7299 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7300 rc = SQLITE_OK;
7301 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00007302 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00007303 }
7304 if( !rc ){
7305 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7306 }
7307 }
7308 }
7309 } while( rc==SQLITE_BUSY && nTries<3 );
7310
7311 return rc;
7312}
7313
7314/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00007315** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7316** lockPath means that the lockPath in the conch file will be used if the
7317** host IDs match, or a new lock path will be generated automatically
7318** and written to the conch file.
7319*/
7320static int proxyTakeConch(unixFile *pFile){
7321 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7322
drh7ed97b92010-01-20 13:07:21 +00007323 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00007324 return SQLITE_OK;
7325 }else{
7326 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00007327 uuid_t myHostID;
7328 int pError = 0;
7329 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00007330 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00007331 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00007332 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00007333 int createConch = 0;
7334 int hostIdMatch = 0;
7335 int readLen = 0;
7336 int tryOldLockPath = 0;
7337 int forceNewLockPath = 0;
7338
drh308c2a52010-05-14 11:30:18 +00007339 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00007340 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007341 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007342
drh7ed97b92010-01-20 13:07:21 +00007343 rc = proxyGetHostID(myHostID, &pError);
7344 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007345 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007346 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007347 }
drh7ed97b92010-01-20 13:07:21 +00007348 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007349 if( rc!=SQLITE_OK ){
7350 goto end_takeconch;
7351 }
drh7ed97b92010-01-20 13:07:21 +00007352 /* read the existing conch file */
7353 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7354 if( readLen<0 ){
7355 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007356 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007357 rc = SQLITE_IOERR_READ;
7358 goto end_takeconch;
7359 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7360 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7361 /* a short read or version format mismatch means we need to create a new
7362 ** conch file.
7363 */
7364 createConch = 1;
7365 }
7366 /* if the host id matches and the lock path already exists in the conch
7367 ** we'll try to use the path there, if we can't open that path, we'll
7368 ** retry with a new auto-generated path
7369 */
7370 do { /* in case we need to try again for an :auto: named lock file */
7371
7372 if( !createConch && !forceNewLockPath ){
7373 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7374 PROXY_HOSTIDLEN);
7375 /* if the conch has data compare the contents */
7376 if( !pCtx->lockProxyPath ){
7377 /* for auto-named local lock file, just check the host ID and we'll
7378 ** use the local lock file path that's already in there
7379 */
7380 if( hostIdMatch ){
7381 size_t pathLen = (readLen - PROXY_PATHINDEX);
7382
7383 if( pathLen>=MAXPATHLEN ){
7384 pathLen=MAXPATHLEN-1;
7385 }
7386 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7387 lockPath[pathLen] = 0;
7388 tempLockPath = lockPath;
7389 tryOldLockPath = 1;
7390 /* create a copy of the lock path if the conch is taken */
7391 goto end_takeconch;
7392 }
7393 }else if( hostIdMatch
7394 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7395 readLen-PROXY_PATHINDEX)
7396 ){
7397 /* conch host and lock path match */
7398 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007399 }
drh7ed97b92010-01-20 13:07:21 +00007400 }
7401
7402 /* if the conch isn't writable and doesn't match, we can't take it */
7403 if( (conchFile->openFlags&O_RDWR) == 0 ){
7404 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007405 goto end_takeconch;
7406 }
drh7ed97b92010-01-20 13:07:21 +00007407
7408 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007409 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007410 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7411 tempLockPath = lockPath;
7412 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007413 }
drh7ed97b92010-01-20 13:07:21 +00007414
7415 /* update conch with host and path (this will fail if other process
7416 ** has a shared lock already), if the host id matches, use the big
7417 ** stick.
drh715ff302008-12-03 22:32:44 +00007418 */
drh7ed97b92010-01-20 13:07:21 +00007419 futimes(conchFile->h, NULL);
7420 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007421 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007422 /* We are trying for an exclusive lock but another thread in this
7423 ** same process is still holding a shared lock. */
7424 rc = SQLITE_BUSY;
7425 } else {
7426 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007427 }
drh715ff302008-12-03 22:32:44 +00007428 }else{
drh4bf66fd2015-02-19 02:43:02 +00007429 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007430 }
drh7ed97b92010-01-20 13:07:21 +00007431 if( rc==SQLITE_OK ){
7432 char writeBuffer[PROXY_MAXCONCHLEN];
7433 int writeSize = 0;
7434
7435 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7436 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7437 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007438 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7439 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007440 }else{
7441 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7442 }
7443 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007444 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007445 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007446 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007447 /* If we created a new conch file (not just updated the contents of a
7448 ** valid conch file), try to match the permissions of the database
7449 */
7450 if( rc==SQLITE_OK && createConch ){
7451 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007452 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007453 if( err==0 ){
7454 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7455 S_IROTH|S_IWOTH);
7456 /* try to match the database file R/W permissions, ignore failure */
7457#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007458 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007459#else
drhff812312011-02-23 13:33:46 +00007460 do{
drhe562be52011-03-02 18:01:10 +00007461 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007462 }while( rc==(-1) && errno==EINTR );
7463 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007464 int code = errno;
7465 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7466 cmode, code, strerror(code));
7467 } else {
7468 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7469 }
7470 }else{
7471 int code = errno;
7472 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7473 err, code, strerror(code));
7474#endif
7475 }
drh715ff302008-12-03 22:32:44 +00007476 }
7477 }
drh7ed97b92010-01-20 13:07:21 +00007478 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7479
7480 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007481 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007482 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007483 int fd;
drh7ed97b92010-01-20 13:07:21 +00007484 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007485 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007486 }
7487 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007488 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007489 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007490 if( fd>=0 ){
7491 pFile->h = fd;
7492 }else{
drh9978c972010-02-23 17:36:32 +00007493 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007494 during locking */
7495 }
7496 }
7497 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7498 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7499 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7500 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7501 /* we couldn't create the proxy lock file with the old lock file path
7502 ** so try again via auto-naming
7503 */
7504 forceNewLockPath = 1;
7505 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007506 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007507 }
7508 }
7509 if( rc==SQLITE_OK ){
7510 /* Need to make a copy of path if we extracted the value
7511 ** from the conch file or the path was allocated on the stack
7512 */
7513 if( tempLockPath ){
7514 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7515 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007516 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007517 }
7518 }
7519 }
7520 if( rc==SQLITE_OK ){
7521 pCtx->conchHeld = 1;
7522
7523 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7524 afpLockingContext *afpCtx;
7525 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7526 afpCtx->dbPath = pCtx->lockProxyPath;
7527 }
7528 } else {
7529 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7530 }
drh308c2a52010-05-14 11:30:18 +00007531 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7532 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007533 return rc;
drh308c2a52010-05-14 11:30:18 +00007534 } while (1); /* in case we need to retry the :auto: lock file -
7535 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007536 }
7537}
7538
7539/*
7540** If pFile holds a lock on a conch file, then release that lock.
7541*/
7542static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007543 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007544 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7545 unixFile *conchFile; /* Name of the conch file */
7546
7547 pCtx = (proxyLockingContext *)pFile->lockingContext;
7548 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007549 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007550 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007551 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007552 if( pCtx->conchHeld>0 ){
7553 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7554 }
drh715ff302008-12-03 22:32:44 +00007555 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007556 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7557 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007558 return rc;
7559}
7560
7561/*
7562** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007563** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007564** Make *pConchPath point to the new name. Return SQLITE_OK on success
7565** or SQLITE_NOMEM if unable to obtain memory.
7566**
7567** The caller is responsible for ensuring that the allocated memory
7568** space is eventually freed.
7569**
7570** *pConchPath is set to NULL if a memory allocation error occurs.
7571*/
7572static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7573 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007574 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007575 char *conchPath; /* buffer in which to construct conch name */
7576
7577 /* Allocate space for the conch filename and initialize the name to
7578 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007579 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007580 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007581 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007582 }
7583 memcpy(conchPath, dbPath, len+1);
7584
7585 /* now insert a "." before the last / character */
7586 for( i=(len-1); i>=0; i-- ){
7587 if( conchPath[i]=='/' ){
7588 i++;
7589 break;
7590 }
7591 }
7592 conchPath[i]='.';
7593 while ( i<len ){
7594 conchPath[i+1]=dbPath[i];
7595 i++;
7596 }
7597
7598 /* append the "-conch" suffix to the file */
7599 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007600 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007601
7602 return SQLITE_OK;
7603}
7604
7605
7606/* Takes a fully configured proxy locking-style unix file and switches
7607** the local lock file path
7608*/
7609static int switchLockProxyPath(unixFile *pFile, const char *path) {
7610 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7611 char *oldPath = pCtx->lockProxyPath;
7612 int rc = SQLITE_OK;
7613
drh308c2a52010-05-14 11:30:18 +00007614 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007615 return SQLITE_BUSY;
7616 }
7617
7618 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7619 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7620 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7621 return SQLITE_OK;
7622 }else{
7623 unixFile *lockProxy = pCtx->lockProxy;
7624 pCtx->lockProxy=NULL;
7625 pCtx->conchHeld = 0;
7626 if( lockProxy!=NULL ){
7627 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7628 if( rc ) return rc;
7629 sqlite3_free(lockProxy);
7630 }
7631 sqlite3_free(oldPath);
7632 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7633 }
7634
7635 return rc;
7636}
7637
7638/*
7639** pFile is a file that has been opened by a prior xOpen call. dbPath
7640** is a string buffer at least MAXPATHLEN+1 characters in size.
7641**
7642** This routine find the filename associated with pFile and writes it
7643** int dbPath.
7644*/
7645static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007646#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007647 if( pFile->pMethod == &afpIoMethods ){
7648 /* afp style keeps a reference to the db path in the filePath field
7649 ** of the struct */
drhea678832008-12-10 19:26:22 +00007650 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007651 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7652 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007653 } else
drh715ff302008-12-03 22:32:44 +00007654#endif
7655 if( pFile->pMethod == &dotlockIoMethods ){
7656 /* dot lock style uses the locking context to store the dot lock
7657 ** file path */
7658 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7659 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7660 }else{
7661 /* all other styles use the locking context to store the db file path */
7662 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007663 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007664 }
7665 return SQLITE_OK;
7666}
7667
7668/*
7669** Takes an already filled in unix file and alters it so all file locking
7670** will be performed on the local proxy lock file. The following fields
7671** are preserved in the locking context so that they can be restored and
7672** the unix structure properly cleaned up at close time:
7673** ->lockingContext
7674** ->pMethod
7675*/
7676static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7677 proxyLockingContext *pCtx;
7678 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7679 char *lockPath=NULL;
7680 int rc = SQLITE_OK;
7681
drh308c2a52010-05-14 11:30:18 +00007682 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007683 return SQLITE_BUSY;
7684 }
7685 proxyGetDbPathForUnixFile(pFile, dbPath);
7686 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7687 lockPath=NULL;
7688 }else{
7689 lockPath=(char *)path;
7690 }
7691
drh308c2a52010-05-14 11:30:18 +00007692 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007693 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007694
drhf3cdcdc2015-04-29 16:50:28 +00007695 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007696 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007697 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007698 }
7699 memset(pCtx, 0, sizeof(*pCtx));
7700
7701 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7702 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007703 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7704 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7705 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7706 ** (c) the file system is read-only, then enable no-locking access.
7707 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7708 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7709 */
7710 struct statfs fsInfo;
7711 struct stat conchInfo;
7712 int goLockless = 0;
7713
drh99ab3b12011-03-02 15:09:07 +00007714 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007715 int err = errno;
7716 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7717 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7718 }
7719 }
7720 if( goLockless ){
7721 pCtx->conchHeld = -1; /* read only FS/ lockless */
7722 rc = SQLITE_OK;
7723 }
7724 }
drh715ff302008-12-03 22:32:44 +00007725 }
7726 if( rc==SQLITE_OK && lockPath ){
7727 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7728 }
7729
7730 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007731 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7732 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007733 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007734 }
7735 }
7736 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007737 /* all memory is allocated, proxys are created and assigned,
7738 ** switch the locking context and pMethod then return.
7739 */
drh715ff302008-12-03 22:32:44 +00007740 pCtx->oldLockingContext = pFile->lockingContext;
7741 pFile->lockingContext = pCtx;
7742 pCtx->pOldMethod = pFile->pMethod;
7743 pFile->pMethod = &proxyIoMethods;
7744 }else{
7745 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007746 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007747 sqlite3_free(pCtx->conchFile);
7748 }
drhd56b1212010-08-11 06:14:15 +00007749 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007750 sqlite3_free(pCtx->conchFilePath);
7751 sqlite3_free(pCtx);
7752 }
drh308c2a52010-05-14 11:30:18 +00007753 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7754 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007755 return rc;
7756}
7757
7758
7759/*
7760** This routine handles sqlite3_file_control() calls that are specific
7761** to proxy locking.
7762*/
7763static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7764 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007765 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007766 unixFile *pFile = (unixFile*)id;
7767 if( pFile->pMethod == &proxyIoMethods ){
7768 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7769 proxyTakeConch(pFile);
7770 if( pCtx->lockProxyPath ){
7771 *(const char **)pArg = pCtx->lockProxyPath;
7772 }else{
7773 *(const char **)pArg = ":auto: (not held)";
7774 }
7775 } else {
7776 *(const char **)pArg = NULL;
7777 }
7778 return SQLITE_OK;
7779 }
drh4bf66fd2015-02-19 02:43:02 +00007780 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007781 unixFile *pFile = (unixFile*)id;
7782 int rc = SQLITE_OK;
7783 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7784 if( pArg==NULL || (const char *)pArg==0 ){
7785 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007786 /* turn off proxy locking - not supported. If support is added for
7787 ** switching proxy locking mode off then it will need to fail if
7788 ** the journal mode is WAL mode.
7789 */
drh715ff302008-12-03 22:32:44 +00007790 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7791 }else{
7792 /* turn off proxy locking - already off - NOOP */
7793 rc = SQLITE_OK;
7794 }
7795 }else{
7796 const char *proxyPath = (const char *)pArg;
7797 if( isProxyStyle ){
7798 proxyLockingContext *pCtx =
7799 (proxyLockingContext*)pFile->lockingContext;
7800 if( !strcmp(pArg, ":auto:")
7801 || (pCtx->lockProxyPath &&
7802 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7803 ){
7804 rc = SQLITE_OK;
7805 }else{
7806 rc = switchLockProxyPath(pFile, proxyPath);
7807 }
7808 }else{
7809 /* turn on proxy file locking */
7810 rc = proxyTransformUnixFile(pFile, proxyPath);
7811 }
7812 }
7813 return rc;
7814 }
7815 default: {
7816 assert( 0 ); /* The call assures that only valid opcodes are sent */
7817 }
7818 }
drh8616cff2019-07-13 16:15:23 +00007819 /*NOTREACHED*/ assert(0);
drh715ff302008-12-03 22:32:44 +00007820 return SQLITE_ERROR;
7821}
7822
7823/*
7824** Within this division (the proxying locking implementation) the procedures
7825** above this point are all utilities. The lock-related methods of the
7826** proxy-locking sqlite3_io_method object follow.
7827*/
7828
7829
7830/*
7831** This routine checks if there is a RESERVED lock held on the specified
7832** file by this or any other process. If such a lock is held, set *pResOut
7833** to a non-zero value otherwise *pResOut is set to zero. The return value
7834** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7835*/
7836static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7837 unixFile *pFile = (unixFile*)id;
7838 int rc = proxyTakeConch(pFile);
7839 if( rc==SQLITE_OK ){
7840 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007841 if( pCtx->conchHeld>0 ){
7842 unixFile *proxy = pCtx->lockProxy;
7843 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7844 }else{ /* conchHeld < 0 is lockless */
7845 pResOut=0;
7846 }
drh715ff302008-12-03 22:32:44 +00007847 }
7848 return rc;
7849}
7850
7851/*
drh308c2a52010-05-14 11:30:18 +00007852** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007853** of the following:
7854**
7855** (1) SHARED_LOCK
7856** (2) RESERVED_LOCK
7857** (3) PENDING_LOCK
7858** (4) EXCLUSIVE_LOCK
7859**
7860** Sometimes when requesting one lock state, additional lock states
7861** are inserted in between. The locking might fail on one of the later
7862** transitions leaving the lock state different from what it started but
7863** still short of its goal. The following chart shows the allowed
7864** transitions and the inserted intermediate states:
7865**
7866** UNLOCKED -> SHARED
7867** SHARED -> RESERVED
7868** SHARED -> (PENDING) -> EXCLUSIVE
7869** RESERVED -> (PENDING) -> EXCLUSIVE
7870** PENDING -> EXCLUSIVE
7871**
7872** This routine will only increase a lock. Use the sqlite3OsUnlock()
7873** routine to lower a locking level.
7874*/
drh308c2a52010-05-14 11:30:18 +00007875static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007876 unixFile *pFile = (unixFile*)id;
7877 int rc = proxyTakeConch(pFile);
7878 if( rc==SQLITE_OK ){
7879 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007880 if( pCtx->conchHeld>0 ){
7881 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007882 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7883 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007884 }else{
7885 /* conchHeld < 0 is lockless */
7886 }
drh715ff302008-12-03 22:32:44 +00007887 }
7888 return rc;
7889}
7890
7891
7892/*
drh308c2a52010-05-14 11:30:18 +00007893** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007894** must be either NO_LOCK or SHARED_LOCK.
7895**
7896** If the locking level of the file descriptor is already at or below
7897** the requested locking level, this routine is a no-op.
7898*/
drh308c2a52010-05-14 11:30:18 +00007899static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007900 unixFile *pFile = (unixFile*)id;
7901 int rc = proxyTakeConch(pFile);
7902 if( rc==SQLITE_OK ){
7903 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007904 if( pCtx->conchHeld>0 ){
7905 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007906 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7907 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007908 }else{
7909 /* conchHeld < 0 is lockless */
7910 }
drh715ff302008-12-03 22:32:44 +00007911 }
7912 return rc;
7913}
7914
7915/*
7916** Close a file that uses proxy locks.
7917*/
7918static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007919 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007920 unixFile *pFile = (unixFile*)id;
7921 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7922 unixFile *lockProxy = pCtx->lockProxy;
7923 unixFile *conchFile = pCtx->conchFile;
7924 int rc = SQLITE_OK;
7925
7926 if( lockProxy ){
7927 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7928 if( rc ) return rc;
7929 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7930 if( rc ) return rc;
7931 sqlite3_free(lockProxy);
7932 pCtx->lockProxy = 0;
7933 }
7934 if( conchFile ){
7935 if( pCtx->conchHeld ){
7936 rc = proxyReleaseConch(pFile);
7937 if( rc ) return rc;
7938 }
7939 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7940 if( rc ) return rc;
7941 sqlite3_free(conchFile);
7942 }
drhd56b1212010-08-11 06:14:15 +00007943 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007944 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007945 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007946 /* restore the original locking context and pMethod then close it */
7947 pFile->lockingContext = pCtx->oldLockingContext;
7948 pFile->pMethod = pCtx->pOldMethod;
7949 sqlite3_free(pCtx);
7950 return pFile->pMethod->xClose(id);
7951 }
7952 return SQLITE_OK;
7953}
7954
7955
7956
drhd2cb50b2009-01-09 21:41:17 +00007957#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007958/*
7959** The proxy locking style is intended for use with AFP filesystems.
7960** And since AFP is only supported on MacOSX, the proxy locking is also
7961** restricted to MacOSX.
7962**
7963**
7964******************* End of the proxy lock implementation **********************
7965******************************************************************************/
7966
drh734c9862008-11-28 15:37:20 +00007967/*
danielk1977e339d652008-06-28 11:23:00 +00007968** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007969**
7970** This routine registers all VFS implementations for unix-like operating
7971** systems. This routine, and the sqlite3_os_end() routine that follows,
7972** should be the only routines in this file that are visible from other
7973** files.
drh6b9d6dd2008-12-03 19:34:47 +00007974**
7975** This routine is called once during SQLite initialization and by a
7976** single thread. The memory allocation and mutex subsystems have not
7977** necessarily been initialized when this routine is called, and so they
7978** should not be used.
drh153c62c2007-08-24 03:51:33 +00007979*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007980int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007981 /*
7982 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007983 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7984 ** to the "finder" function. (pAppData is a pointer to a pointer because
7985 ** silly C90 rules prohibit a void* from being cast to a function pointer
7986 ** and so we have to go through the intermediate pointer to avoid problems
7987 ** when compiling with -pedantic-errors on GCC.)
7988 **
7989 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007990 ** finder-function. The finder-function returns a pointer to the
7991 ** sqlite_io_methods object that implements the desired locking
7992 ** behaviors. See the division above that contains the IOMETHODS
7993 ** macro for addition information on finder-functions.
7994 **
7995 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7996 ** object. But the "autolockIoFinder" available on MacOSX does a little
7997 ** more than that; it looks at the filesystem type that hosts the
7998 ** database file and tries to choose an locking method appropriate for
7999 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00008000 */
drh7708e972008-11-29 00:56:52 +00008001 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00008002 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00008003 sizeof(unixFile), /* szOsFile */ \
8004 MAX_PATHNAME, /* mxPathname */ \
8005 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00008006 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00008007 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00008008 unixOpen, /* xOpen */ \
8009 unixDelete, /* xDelete */ \
8010 unixAccess, /* xAccess */ \
8011 unixFullPathname, /* xFullPathname */ \
8012 unixDlOpen, /* xDlOpen */ \
8013 unixDlError, /* xDlError */ \
8014 unixDlSym, /* xDlSym */ \
8015 unixDlClose, /* xDlClose */ \
8016 unixRandomness, /* xRandomness */ \
8017 unixSleep, /* xSleep */ \
8018 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00008019 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00008020 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00008021 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00008022 unixGetSystemCall, /* xGetSystemCall */ \
8023 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00008024 }
8025
drh6b9d6dd2008-12-03 19:34:47 +00008026 /*
8027 ** All default VFSes for unix are contained in the following array.
8028 **
8029 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
8030 ** by the SQLite core when the VFS is registered. So the following
8031 ** array cannot be const.
8032 */
danielk1977e339d652008-06-28 11:23:00 +00008033 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00008034#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00008035 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00008036#elif OS_VXWORKS
8037 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00008038#else
8039 UNIXVFS("unix", posixIoFinder ),
8040#endif
8041 UNIXVFS("unix-none", nolockIoFinder ),
8042 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00008043 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00008044#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00008045 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00008046#endif
drhe89b2912015-03-03 20:42:01 +00008047#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00008048 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00008049#endif
drhe89b2912015-03-03 20:42:01 +00008050#if SQLITE_ENABLE_LOCKING_STYLE
8051 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00008052#endif
drhd2cb50b2009-01-09 21:41:17 +00008053#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00008054 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00008055 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00008056 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00008057#endif
drh153c62c2007-08-24 03:51:33 +00008058 };
drh6b9d6dd2008-12-03 19:34:47 +00008059 unsigned int i; /* Loop counter */
8060
drh2aa5a002011-04-13 13:42:25 +00008061 /* Double-check that the aSyscall[] array has been constructed
8062 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00008063 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00008064
drh6b9d6dd2008-12-03 19:34:47 +00008065 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00008066 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00008067 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00008068 }
drh56115892018-02-05 16:39:12 +00008069 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
drh187e2e42021-05-19 16:55:28 +00008070
8071 /* Validate lock assumptions */
8072 assert( SQLITE_SHM_NLOCK==8 ); /* Number of available locks */
8073 assert( UNIX_SHM_BASE==120 ); /* Start of locking area */
8074 /* Locks:
drh04f4b682021-05-19 19:27:42 +00008075 ** WRITE UNIX_SHM_BASE 120
8076 ** CKPT UNIX_SHM_BASE+1 121
8077 ** RECOVER UNIX_SHM_BASE+2 122
8078 ** READ-0 UNIX_SHM_BASE+3 123
8079 ** READ-1 UNIX_SHM_BASE+4 124
8080 ** READ-2 UNIX_SHM_BASE+5 125
8081 ** READ-3 UNIX_SHM_BASE+6 126
8082 ** READ-4 UNIX_SHM_BASE+7 127
8083 ** DMS UNIX_SHM_BASE+8 128
8084 */
drh187e2e42021-05-19 16:55:28 +00008085 assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */
danielk1977c0fa4c52008-06-25 17:19:00 +00008086 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00008087}
danielk1977e339d652008-06-28 11:23:00 +00008088
8089/*
drh6b9d6dd2008-12-03 19:34:47 +00008090** Shutdown the operating system interface.
8091**
8092** Some operating systems might need to do some cleanup in this routine,
8093** to release dynamically allocated objects. But not on unix.
8094** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00008095*/
danielk1977c0fa4c52008-06-25 17:19:00 +00008096int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00008097 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00008098 return SQLITE_OK;
8099}
drhdce8bdb2007-08-16 13:01:44 +00008100
danielk197729bafea2008-06-26 10:41:19 +00008101#endif /* SQLITE_OS_UNIX */