blob: c3359f1bc740d7c4589ea2488b86bb9ddd7be5bf [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*/
drh6b013af2022-09-12 12:41:07 +000090#include <sys/types.h> /* amalgamator: keep */
91#include <sys/stat.h> /* amalgamator: keep */
drh9cbe6352005-11-29 03:13:21 +000092#include <fcntl.h>
danefe16972017-07-20 19:49:14 +000093#include <sys/ioctl.h>
drh6b013af2022-09-12 12:41:07 +000094#include <unistd.h> /* amalgamator: keep */
drhbbd42a62004-05-22 17:41:58 +000095#include <time.h>
drhb126ec12022-09-12 19:33:20 +000096#include <sys/time.h> /* amalgamator: keep */
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;
drhb1026ae2022-12-06 13:12:33 +0000689 if( (f & (O_EXCL|O_CREAT))==(O_EXCL|O_CREAT) ){
690 (void)osUnlink(z);
691 }
drh5128d002013-08-30 06:20:23 +0000692 osClose(fd);
693 sqlite3_log(SQLITE_WARNING,
694 "attempt to open \"%s\" as file descriptor %d", z, fd);
695 fd = -1;
drh0ba36212020-02-13 13:45:04 +0000696 if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
drh5128d002013-08-30 06:20:23 +0000697 }
drhe1186ab2013-01-04 20:45:13 +0000698 if( fd>=0 ){
699 if( m!=0 ){
700 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000701 if( osFstat(fd, &statbuf)==0
702 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000703 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000704 ){
drhe1186ab2013-01-04 20:45:13 +0000705 osFchmod(fd, m);
706 }
707 }
drh5adc60b2012-04-14 13:25:11 +0000708#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000709 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000710#endif
drhe1186ab2013-01-04 20:45:13 +0000711 }
drh5adc60b2012-04-14 13:25:11 +0000712 return fd;
drhad4f1e52011-03-04 15:43:57 +0000713}
danielk197713adf8a2004-06-03 16:08:41 +0000714
drh107886a2008-11-21 22:21:50 +0000715/*
dan9359c7b2009-08-21 08:29:10 +0000716** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000717** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000718** vxworksFileId objects used by this file, all of which may be
719** shared by multiple threads.
720**
721** Function unixMutexHeld() is used to assert() that the global mutex
722** is held when required. This function is only used as part of assert()
723** statements. e.g.
724**
725** unixEnterMutex()
726** assert( unixMutexHeld() );
727** unixEnterLeave()
drh095908e2018-08-13 20:46:18 +0000728**
729** To prevent deadlock, the global unixBigLock must must be acquired
730** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
731** OK to get the pLockMutex without holding unixBigLock first, but if
732** that happens, the unixBigLock mutex must not be acquired until after
733** pLockMutex is released.
734**
735** OK: enter(unixBigLock), enter(pLockInfo)
736** OK: enter(unixBigLock)
737** OK: enter(pLockInfo)
738** ERROR: enter(pLockInfo), enter(unixBigLock)
drh107886a2008-11-21 22:21:50 +0000739*/
drh56115892018-02-05 16:39:12 +0000740static sqlite3_mutex *unixBigLock = 0;
drh107886a2008-11-21 22:21:50 +0000741static void unixEnterMutex(void){
drh095908e2018-08-13 20:46:18 +0000742 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
drh56115892018-02-05 16:39:12 +0000743 sqlite3_mutex_enter(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000744}
745static void unixLeaveMutex(void){
drh095908e2018-08-13 20:46:18 +0000746 assert( sqlite3_mutex_held(unixBigLock) );
drh56115892018-02-05 16:39:12 +0000747 sqlite3_mutex_leave(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000748}
dan9359c7b2009-08-21 08:29:10 +0000749#ifdef SQLITE_DEBUG
750static int unixMutexHeld(void) {
drh56115892018-02-05 16:39:12 +0000751 return sqlite3_mutex_held(unixBigLock);
dan9359c7b2009-08-21 08:29:10 +0000752}
753#endif
drh107886a2008-11-21 22:21:50 +0000754
drh734c9862008-11-28 15:37:20 +0000755
mistachkinfb383e92015-04-16 03:24:38 +0000756#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000757/*
758** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000759** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000760** integer lock-type.
761*/
drh308c2a52010-05-14 11:30:18 +0000762static const char *azFileLock(int eFileLock){
763 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000764 case NO_LOCK: return "NONE";
765 case SHARED_LOCK: return "SHARED";
766 case RESERVED_LOCK: return "RESERVED";
767 case PENDING_LOCK: return "PENDING";
768 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000769 }
770 return "ERROR";
771}
772#endif
773
774#ifdef SQLITE_LOCK_TRACE
775/*
776** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000777**
drh734c9862008-11-28 15:37:20 +0000778** This routine is used for troubleshooting locks on multithreaded
779** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
780** command-line option on the compiler. This code is normally
781** turned off.
782*/
783static int lockTrace(int fd, int op, struct flock *p){
784 char *zOpName, *zType;
785 int s;
786 int savedErrno;
787 if( op==F_GETLK ){
788 zOpName = "GETLK";
789 }else if( op==F_SETLK ){
790 zOpName = "SETLK";
791 }else{
drh99ab3b12011-03-02 15:09:07 +0000792 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000793 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
794 return s;
795 }
796 if( p->l_type==F_RDLCK ){
797 zType = "RDLCK";
798 }else if( p->l_type==F_WRLCK ){
799 zType = "WRLCK";
800 }else if( p->l_type==F_UNLCK ){
801 zType = "UNLCK";
802 }else{
803 assert( 0 );
804 }
805 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000806 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000807 savedErrno = errno;
808 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
809 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
810 (int)p->l_pid, s);
811 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
812 struct flock l2;
813 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000814 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000815 if( l2.l_type==F_RDLCK ){
816 zType = "RDLCK";
817 }else if( l2.l_type==F_WRLCK ){
818 zType = "WRLCK";
819 }else if( l2.l_type==F_UNLCK ){
820 zType = "UNLCK";
821 }else{
822 assert( 0 );
823 }
824 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
825 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
826 }
827 errno = savedErrno;
828 return s;
829}
drh99ab3b12011-03-02 15:09:07 +0000830#undef osFcntl
831#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000832#endif /* SQLITE_LOCK_TRACE */
833
drhff812312011-02-23 13:33:46 +0000834/*
835** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000836**
drhe6d41732015-02-21 00:49:00 +0000837** All calls to ftruncate() within this file should be made through
838** this wrapper. On the Android platform, bypassing the logic below
839** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000840*/
drhff812312011-02-23 13:33:46 +0000841static int robust_ftruncate(int h, sqlite3_int64 sz){
842 int rc;
dan2ee53412014-09-06 16:49:40 +0000843#ifdef __ANDROID__
844 /* On Android, ftruncate() always uses 32-bit offsets, even if
845 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000846 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000847 ** such attempts. */
848 if( sz>(sqlite3_int64)0x7FFFFFFF ){
849 rc = SQLITE_OK;
850 }else
851#endif
drh99ab3b12011-03-02 15:09:07 +0000852 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000853 return rc;
854}
drh734c9862008-11-28 15:37:20 +0000855
856/*
857** This routine translates a standard POSIX errno code into something
858** useful to the clients of the sqlite3 functions. Specifically, it is
859** intended to translate a variety of "try again" errors into SQLITE_BUSY
860** and a variety of "please close the file descriptor NOW" errors into
861** SQLITE_IOERR
862**
863** Errors during initialization of locks, or file system support for locks,
864** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
865*/
866static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000867 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
868 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
869 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
870 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000871 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000872 case EACCES:
drh734c9862008-11-28 15:37:20 +0000873 case EAGAIN:
874 case ETIMEDOUT:
875 case EBUSY:
876 case EINTR:
877 case ENOLCK:
878 /* random NFS retry error, unless during file system support
879 * introspection, in which it actually means what it says */
880 return SQLITE_BUSY;
881
drh734c9862008-11-28 15:37:20 +0000882 case EPERM:
883 return SQLITE_PERM;
884
drh734c9862008-11-28 15:37:20 +0000885 default:
886 return sqliteIOErr;
887 }
888}
889
890
drh734c9862008-11-28 15:37:20 +0000891/******************************************************************************
892****************** Begin Unique File ID Utility Used By VxWorks ***************
893**
894** On most versions of unix, we can get a unique ID for a file by concatenating
895** the device number and the inode number. But this does not work on VxWorks.
896** On VxWorks, a unique file id must be based on the canonical filename.
897**
898** A pointer to an instance of the following structure can be used as a
899** unique file ID in VxWorks. Each instance of this structure contains
900** a copy of the canonical filename. There is also a reference count.
901** The structure is reclaimed when the number of pointers to it drops to
902** zero.
903**
904** There are never very many files open at one time and lookups are not
905** a performance-critical path, so it is sufficient to put these
906** structures on a linked list.
907*/
908struct vxworksFileId {
909 struct vxworksFileId *pNext; /* Next in a list of them all */
910 int nRef; /* Number of references to this one */
911 int nName; /* Length of the zCanonicalName[] string */
912 char *zCanonicalName; /* Canonical filename */
913};
914
915#if OS_VXWORKS
916/*
drh9b35ea62008-11-29 02:20:26 +0000917** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000918** variable:
919*/
920static struct vxworksFileId *vxworksFileList = 0;
921
922/*
923** Simplify a filename into its canonical form
924** by making the following changes:
925**
926** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000927** * convert /./ into just /
928** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000929**
930** Changes are made in-place. Return the new name length.
931**
932** The original filename is in z[0..n-1]. Return the number of
933** characters in the simplified name.
934*/
935static int vxworksSimplifyName(char *z, int n){
936 int i, j;
937 while( n>1 && z[n-1]=='/' ){ n--; }
938 for(i=j=0; i<n; i++){
939 if( z[i]=='/' ){
940 if( z[i+1]=='/' ) continue;
941 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
942 i += 1;
943 continue;
944 }
945 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
946 while( j>0 && z[j-1]!='/' ){ j--; }
947 if( j>0 ){ j--; }
948 i += 2;
949 continue;
950 }
951 }
952 z[j++] = z[i];
953 }
954 z[j] = 0;
955 return j;
956}
957
958/*
959** Find a unique file ID for the given absolute pathname. Return
960** a pointer to the vxworksFileId object. This pointer is the unique
961** file ID.
962**
963** The nRef field of the vxworksFileId object is incremented before
964** the object is returned. A new vxworksFileId object is created
965** and added to the global list if necessary.
966**
967** If a memory allocation error occurs, return NULL.
968*/
969static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
970 struct vxworksFileId *pNew; /* search key and new file ID */
971 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
972 int n; /* Length of zAbsoluteName string */
973
974 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000975 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000976 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000977 if( pNew==0 ) return 0;
978 pNew->zCanonicalName = (char*)&pNew[1];
979 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
980 n = vxworksSimplifyName(pNew->zCanonicalName, n);
981
982 /* Search for an existing entry that matching the canonical name.
983 ** If found, increment the reference count and return a pointer to
984 ** the existing file ID.
985 */
986 unixEnterMutex();
987 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
988 if( pCandidate->nName==n
989 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
990 ){
991 sqlite3_free(pNew);
992 pCandidate->nRef++;
993 unixLeaveMutex();
994 return pCandidate;
995 }
996 }
997
998 /* No match was found. We will make a new file ID */
999 pNew->nRef = 1;
1000 pNew->nName = n;
1001 pNew->pNext = vxworksFileList;
1002 vxworksFileList = pNew;
1003 unixLeaveMutex();
1004 return pNew;
1005}
1006
1007/*
1008** Decrement the reference count on a vxworksFileId object. Free
1009** the object when the reference count reaches zero.
1010*/
1011static void vxworksReleaseFileId(struct vxworksFileId *pId){
1012 unixEnterMutex();
1013 assert( pId->nRef>0 );
1014 pId->nRef--;
1015 if( pId->nRef==0 ){
1016 struct vxworksFileId **pp;
1017 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
1018 assert( *pp==pId );
1019 *pp = pId->pNext;
1020 sqlite3_free(pId);
1021 }
1022 unixLeaveMutex();
1023}
1024#endif /* OS_VXWORKS */
1025/*************** End of Unique File ID Utility Used By VxWorks ****************
1026******************************************************************************/
1027
1028
1029/******************************************************************************
1030*************************** Posix Advisory Locking ****************************
1031**
drh9b35ea62008-11-29 02:20:26 +00001032** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +00001033** section 6.5.2.2 lines 483 through 490 specify that when a process
1034** sets or clears a lock, that operation overrides any prior locks set
1035** by the same process. It does not explicitly say so, but this implies
1036** that it overrides locks set by the same process using a different
1037** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +00001038**
1039** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +00001040** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1041**
1042** Suppose ./file1 and ./file2 are really the same file (because
1043** one is a hard or symbolic link to the other) then if you set
1044** an exclusive lock on fd1, then try to get an exclusive lock
1045** on fd2, it works. I would have expected the second lock to
1046** fail since there was already a lock on the file due to fd1.
1047** But not so. Since both locks came from the same process, the
1048** second overrides the first, even though they were on different
1049** file descriptors opened on different file names.
1050**
drh734c9862008-11-28 15:37:20 +00001051** This means that we cannot use POSIX locks to synchronize file access
1052** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001053** to synchronize access for threads in separate processes, but not
1054** threads within the same process.
1055**
1056** To work around the problem, SQLite has to manage file locks internally
1057** on its own. Whenever a new database is opened, we have to find the
1058** specific inode of the database file (the inode is determined by the
1059** st_dev and st_ino fields of the stat structure that fstat() fills in)
1060** and check for locks already existing on that inode. When locks are
1061** created or removed, we have to look at our own internal record of the
1062** locks to see if another thread has previously set a lock on that same
1063** inode.
1064**
drh9b35ea62008-11-29 02:20:26 +00001065** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1066** For VxWorks, we have to use the alternative unique ID system based on
1067** canonical filename and implemented in the previous division.)
1068**
danielk1977ad94b582007-08-20 06:44:22 +00001069** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001070** descriptor. It is now a structure that holds the integer file
1071** descriptor and a pointer to a structure that describes the internal
1072** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001073** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001074** point to the same locking structure. The locking structure keeps
1075** a reference count (so we will know when to delete it) and a "cnt"
1076** field that tells us its internal lock status. cnt==0 means the
1077** file is unlocked. cnt==-1 means the file has an exclusive lock.
1078** cnt>0 means there are cnt shared locks on the file.
1079**
1080** Any attempt to lock or unlock a file first checks the locking
1081** structure. The fcntl() system call is only invoked to set a
1082** POSIX lock if the internal lock structure transitions between
1083** a locked and an unlocked state.
1084**
drh734c9862008-11-28 15:37:20 +00001085** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001086**
1087** If you close a file descriptor that points to a file that has locks,
1088** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001089** released. To work around this problem, each unixInodeInfo object
1090** maintains a count of the number of pending locks on tha inode.
1091** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001092** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001093** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001094** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001095** be closed and that list is walked (and cleared) when the last lock
1096** clears.
1097**
drh9b35ea62008-11-29 02:20:26 +00001098** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001099**
drh9b35ea62008-11-29 02:20:26 +00001100** Many older versions of linux use the LinuxThreads library which is
1101** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001102** A cannot be modified or overridden by a different thread B.
1103** Only thread A can modify the lock. Locking behavior is correct
1104** if the appliation uses the newer Native Posix Thread Library (NPTL)
1105** on linux - with NPTL a lock created by thread A can override locks
1106** in thread B. But there is no way to know at compile-time which
1107** threading library is being used. So there is no way to know at
1108** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001109** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001110** current process.
drh5fdae772004-06-29 03:29:00 +00001111**
drh8af6c222010-05-14 12:43:01 +00001112** SQLite used to support LinuxThreads. But support for LinuxThreads
1113** was dropped beginning with version 3.7.0. SQLite will still work with
1114** LinuxThreads provided that (1) there is no more than one connection
1115** per database file in the same process and (2) database connections
1116** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001117*/
1118
1119/*
1120** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001121** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001122*/
1123struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001124 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001125#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001126 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001127#else
drh25ef7f52016-12-05 20:06:45 +00001128 /* We are told that some versions of Android contain a bug that
1129 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1130 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1131 ** To work around this, always allocate 64-bits for the inode number.
1132 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1133 ** but that should not be a big deal. */
1134 /* WAS: ino_t ino; */
1135 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001136#endif
1137};
1138
1139/*
drhbbd42a62004-05-22 17:41:58 +00001140** An instance of the following structure is allocated for each open
drh24efa542018-10-02 19:36:40 +00001141** inode.
drhbbd42a62004-05-22 17:41:58 +00001142**
danielk1977ad94b582007-08-20 06:44:22 +00001143** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001144** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001145** object keeps a count of the number of unixFile pointing to it.
drhda6dc242018-07-23 21:10:37 +00001146**
1147** Mutex rules:
1148**
drh095908e2018-08-13 20:46:18 +00001149** (1) Only the pLockMutex mutex must be held in order to read or write
drhda6dc242018-07-23 21:10:37 +00001150** any of the locking fields:
drhef52b362018-08-13 22:50:34 +00001151** nShared, nLock, eFileLock, bProcessLock, pUnused
drhda6dc242018-07-23 21:10:37 +00001152**
1153** (2) When nRef>0, then the following fields are unchanging and can
1154** be read (but not written) without holding any mutex:
1155** fileId, pLockMutex
1156**
drhef52b362018-08-13 22:50:34 +00001157** (3) With the exceptions above, all the fields may only be read
drhda6dc242018-07-23 21:10:37 +00001158** or written while holding the global unixBigLock mutex.
drh095908e2018-08-13 20:46:18 +00001159**
1160** Deadlock prevention: The global unixBigLock mutex may not
1161** be acquired while holding the pLockMutex mutex. If both unixBigLock
1162** and pLockMutex are needed, then unixBigLock must be acquired first.
drhbbd42a62004-05-22 17:41:58 +00001163*/
drh8af6c222010-05-14 12:43:01 +00001164struct unixInodeInfo {
1165 struct unixFileId fileId; /* The lookup key */
drhda6dc242018-07-23 21:10:37 +00001166 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1167 int nShared; /* Number of SHARED locks held */
1168 int nLock; /* Number of outstanding file locks */
1169 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1170 unsigned char bProcessLock; /* An exclusive process lock is held */
drhef52b362018-08-13 22:50:34 +00001171 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh734c9862008-11-28 15:37:20 +00001172 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001173 unixShmNode *pShmNode; /* Shared memory associated with this inode */
drhd91c68f2010-05-14 14:52:25 +00001174 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1175 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001176#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001177 unsigned long long sharedByte; /* for AFP simulated shared lock */
1178#endif
drh6c7d5c52008-11-21 20:32:33 +00001179#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001180 sem_t *pSem; /* Named POSIX semaphore */
1181 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001182#endif
drhbbd42a62004-05-22 17:41:58 +00001183};
1184
drhda0e7682008-07-30 15:27:54 +00001185/*
drh8af6c222010-05-14 12:43:01 +00001186** A lists of all unixInodeInfo objects.
drh24efa542018-10-02 19:36:40 +00001187**
1188** Must hold unixBigLock in order to read or write this variable.
drhbbd42a62004-05-22 17:41:58 +00001189*/
drhc68886b2017-08-18 16:09:52 +00001190static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
drh095908e2018-08-13 20:46:18 +00001191
1192#ifdef SQLITE_DEBUG
1193/*
drh24efa542018-10-02 19:36:40 +00001194** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
1195** This routine is used only within assert() to help verify correct mutex
1196** usage.
drh095908e2018-08-13 20:46:18 +00001197*/
1198int unixFileMutexHeld(unixFile *pFile){
1199 assert( pFile->pInode );
1200 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1201}
1202int unixFileMutexNotheld(unixFile *pFile){
1203 assert( pFile->pInode );
1204 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1205}
1206#endif
drh5fdae772004-06-29 03:29:00 +00001207
drh5fdae772004-06-29 03:29:00 +00001208/*
dane18d4952011-02-21 11:46:24 +00001209**
drhaaeaa182015-11-24 15:12:47 +00001210** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001211** unixLogError().
1212**
1213** It is invoked after an error occurs in an OS function and errno has been
1214** set. It logs a message using sqlite3_log() containing the current value of
1215** errno and, if possible, the human-readable equivalent from strerror() or
1216** strerror_r().
1217**
1218** The first argument passed to the macro should be the error code that
1219** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1220** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001221** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001222** if any.
1223*/
drh0e9365c2011-03-02 02:08:13 +00001224#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1225static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001226 int errcode, /* SQLite error code */
1227 const char *zFunc, /* Name of OS function that failed */
1228 const char *zPath, /* File path associated with error */
1229 int iLine /* Source line number where error occurred */
1230){
1231 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001232 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001233
1234 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1235 ** the strerror() function to obtain the human-readable error message
1236 ** equivalent to errno. Otherwise, use strerror_r().
1237 */
1238#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1239 char aErr[80];
1240 memset(aErr, 0, sizeof(aErr));
1241 zErr = aErr;
1242
1243 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001244 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001245 ** returns a pointer to a buffer containing the error message. That pointer
1246 ** may point to aErr[], or it may point to some static storage somewhere.
1247 ** Otherwise, assume that the system provides the POSIX version of
1248 ** strerror_r(), which always writes an error message into aErr[].
1249 **
1250 ** If the code incorrectly assumes that it is the POSIX version that is
1251 ** available, the error message will often be an empty string. Not a
1252 ** huge problem. Incorrectly concluding that the GNU version is available
1253 ** could lead to a segfault though.
1254 */
1255#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1256 zErr =
1257# endif
drh0e9365c2011-03-02 02:08:13 +00001258 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001259
1260#elif SQLITE_THREADSAFE
1261 /* This is a threadsafe build, but strerror_r() is not available. */
1262 zErr = "";
1263#else
1264 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001265 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001266#endif
1267
drh0e9365c2011-03-02 02:08:13 +00001268 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001269 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001270 "os_unix.c:%d: (%d) %s(%s) - %s",
1271 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001272 );
1273
1274 return errcode;
1275}
1276
drh0e9365c2011-03-02 02:08:13 +00001277/*
1278** Close a file descriptor.
1279**
1280** We assume that close() almost always works, since it is only in a
1281** very sick application or on a very sick platform that it might fail.
1282** If it does fail, simply leak the file descriptor, but do log the
1283** error.
1284**
1285** Note that it is not safe to retry close() after EINTR since the
1286** file descriptor might have already been reused by another thread.
1287** So we don't even try to recover from an EINTR. Just log the error
1288** and move on.
1289*/
1290static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001291 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001292 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1293 pFile ? pFile->zPath : 0, lineno);
1294 }
1295}
dane18d4952011-02-21 11:46:24 +00001296
1297/*
drhe6d41732015-02-21 00:49:00 +00001298** Set the pFile->lastErrno. Do this in a subroutine as that provides
1299** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001300*/
1301static void storeLastErrno(unixFile *pFile, int error){
1302 pFile->lastErrno = error;
1303}
1304
1305/*
danb0ac3e32010-06-16 10:55:42 +00001306** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001307*/
drh0e9365c2011-03-02 02:08:13 +00001308static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001309 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001310 UnixUnusedFd *p;
1311 UnixUnusedFd *pNext;
drhef52b362018-08-13 22:50:34 +00001312 assert( unixFileMutexHeld(pFile) );
danb0ac3e32010-06-16 10:55:42 +00001313 for(p=pInode->pUnused; p; p=pNext){
1314 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001315 robust_close(pFile, p->fd, __LINE__);
1316 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001317 }
drh0e9365c2011-03-02 02:08:13 +00001318 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001319}
1320
1321/*
drh8af6c222010-05-14 12:43:01 +00001322** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001323**
drh24efa542018-10-02 19:36:40 +00001324** The global mutex must be held when this routine is called, but the mutex
1325** on the inode being deleted must NOT be held.
drh6c7d5c52008-11-21 20:32:33 +00001326*/
danb0ac3e32010-06-16 10:55:42 +00001327static void releaseInodeInfo(unixFile *pFile){
1328 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001329 assert( unixMutexHeld() );
drh095908e2018-08-13 20:46:18 +00001330 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00001331 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001332 pInode->nRef--;
1333 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001334 assert( pInode->pShmNode==0 );
drhef52b362018-08-13 22:50:34 +00001335 sqlite3_mutex_enter(pInode->pLockMutex);
danb0ac3e32010-06-16 10:55:42 +00001336 closePendingFds(pFile);
drhef52b362018-08-13 22:50:34 +00001337 sqlite3_mutex_leave(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001338 if( pInode->pPrev ){
1339 assert( pInode->pPrev->pNext==pInode );
1340 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001341 }else{
drh8af6c222010-05-14 12:43:01 +00001342 assert( inodeList==pInode );
1343 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001344 }
drh8af6c222010-05-14 12:43:01 +00001345 if( pInode->pNext ){
1346 assert( pInode->pNext->pPrev==pInode );
1347 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001348 }
drhda6dc242018-07-23 21:10:37 +00001349 sqlite3_mutex_free(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001350 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001351 }
drhbbd42a62004-05-22 17:41:58 +00001352 }
1353}
1354
1355/*
drh8af6c222010-05-14 12:43:01 +00001356** Given a file descriptor, locate the unixInodeInfo object that
1357** describes that file descriptor. Create a new one if necessary. The
1358** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001359**
drh24efa542018-10-02 19:36:40 +00001360** The global mutex must held when calling this routine.
dan9359c7b2009-08-21 08:29:10 +00001361**
drh6c7d5c52008-11-21 20:32:33 +00001362** Return an appropriate error code.
1363*/
drh8af6c222010-05-14 12:43:01 +00001364static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001365 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001366 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001367){
1368 int rc; /* System call return code */
1369 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001370 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1371 struct stat statbuf; /* Low-level file information */
1372 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001373
dan9359c7b2009-08-21 08:29:10 +00001374 assert( unixMutexHeld() );
1375
drh6c7d5c52008-11-21 20:32:33 +00001376 /* Get low-level information about the file that we can used to
1377 ** create a unique name for the file.
1378 */
1379 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001380 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001381 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001382 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001383#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001384 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1385#endif
1386 return SQLITE_IOERR;
1387 }
1388
drheb0d74f2009-02-03 15:27:02 +00001389#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001390 /* On OS X on an msdos filesystem, the inode number is reported
1391 ** incorrectly for zero-size files. See ticket #3260. To work
1392 ** around this problem (we consider it a bug in OS X, not SQLite)
1393 ** we always increase the file size to 1 by writing a single byte
1394 ** prior to accessing the inode number. The one byte written is
1395 ** an ASCII 'S' character which also happens to be the first byte
1396 ** in the header of every SQLite database. In this way, if there
1397 ** is a race condition such that another thread has already populated
1398 ** the first page of the database, no damage is done.
1399 */
drh7ed97b92010-01-20 13:07:21 +00001400 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001401 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001402 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001403 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001404 return SQLITE_IOERR;
1405 }
drh99ab3b12011-03-02 15:09:07 +00001406 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001407 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001408 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001409 return SQLITE_IOERR;
1410 }
1411 }
drheb0d74f2009-02-03 15:27:02 +00001412#endif
drh6c7d5c52008-11-21 20:32:33 +00001413
drh8af6c222010-05-14 12:43:01 +00001414 memset(&fileId, 0, sizeof(fileId));
1415 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001416#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001417 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001418#else
drh25ef7f52016-12-05 20:06:45 +00001419 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001420#endif
drh24efa542018-10-02 19:36:40 +00001421 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001422 pInode = inodeList;
1423 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1424 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001425 }
drh8af6c222010-05-14 12:43:01 +00001426 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001427 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001428 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001429 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001430 }
drh8af6c222010-05-14 12:43:01 +00001431 memset(pInode, 0, sizeof(*pInode));
1432 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
drh6886d6d2018-07-23 22:55:10 +00001433 if( sqlite3GlobalConfig.bCoreMutex ){
1434 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1435 if( pInode->pLockMutex==0 ){
1436 sqlite3_free(pInode);
1437 return SQLITE_NOMEM_BKPT;
1438 }
1439 }
drh8af6c222010-05-14 12:43:01 +00001440 pInode->nRef = 1;
drh24efa542018-10-02 19:36:40 +00001441 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001442 pInode->pNext = inodeList;
1443 pInode->pPrev = 0;
1444 if( inodeList ) inodeList->pPrev = pInode;
1445 inodeList = pInode;
1446 }else{
1447 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001448 }
drh8af6c222010-05-14 12:43:01 +00001449 *ppInode = pInode;
1450 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001451}
drh6c7d5c52008-11-21 20:32:33 +00001452
drhb959a012013-12-07 12:29:22 +00001453/*
1454** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1455*/
1456static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001457#if OS_VXWORKS
1458 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1459#else
drhb959a012013-12-07 12:29:22 +00001460 struct stat buf;
1461 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001462 (osStat(pFile->zPath, &buf)!=0
1463 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001464#endif
drhb959a012013-12-07 12:29:22 +00001465}
1466
aswift5b1a2562008-08-22 00:22:35 +00001467
1468/*
drhfbc7e882013-04-11 01:16:15 +00001469** Check a unixFile that is a database. Verify the following:
1470**
1471** (1) There is exactly one hard link on the file
1472** (2) The file is not a symbolic link
1473** (3) The file has not been renamed or unlinked
1474**
1475** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1476*/
1477static void verifyDbFile(unixFile *pFile){
1478 struct stat buf;
1479 int rc;
drh86151e82015-12-08 14:37:16 +00001480
1481 /* These verifications occurs for the main database only */
1482 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1483
drhfbc7e882013-04-11 01:16:15 +00001484 rc = osFstat(pFile->h, &buf);
1485 if( rc!=0 ){
1486 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001487 return;
1488 }
drh6369bc32016-03-21 16:06:42 +00001489 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001490 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001491 return;
1492 }
1493 if( buf.st_nlink>1 ){
1494 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001495 return;
1496 }
drhb959a012013-12-07 12:29:22 +00001497 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001498 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001499 return;
1500 }
1501}
1502
1503
1504/*
danielk197713adf8a2004-06-03 16:08:41 +00001505** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001506** file by this or any other process. If such a lock is held, set *pResOut
1507** to a non-zero value otherwise *pResOut is set to zero. The return value
1508** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001509*/
danielk1977861f7452008-06-05 11:39:11 +00001510static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001511 int rc = SQLITE_OK;
1512 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001513 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001514
danielk1977861f7452008-06-05 11:39:11 +00001515 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1516
drh054889e2005-11-30 03:20:31 +00001517 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001518 assert( pFile->eFileLock<=SHARED_LOCK );
drhda6dc242018-07-23 21:10:37 +00001519 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
danielk197713adf8a2004-06-03 16:08:41 +00001520
1521 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001522 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001523 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001524 }
1525
drh2ac3ee92004-06-07 16:27:46 +00001526 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001527 */
danielk197709480a92009-02-09 05:32:32 +00001528#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001529 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001530 struct flock lock;
1531 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001532 lock.l_start = RESERVED_BYTE;
1533 lock.l_len = 1;
1534 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001535 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1536 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001537 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001538 } else if( lock.l_type!=F_UNLCK ){
1539 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001540 }
1541 }
danielk197709480a92009-02-09 05:32:32 +00001542#endif
danielk197713adf8a2004-06-03 16:08:41 +00001543
drhda6dc242018-07-23 21:10:37 +00001544 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001545 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001546
aswift5b1a2562008-08-22 00:22:35 +00001547 *pResOut = reserved;
1548 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001549}
1550
drhddcfe922020-09-15 12:29:35 +00001551/* Forward declaration*/
1552static int unixSleep(sqlite3_vfs*,int);
1553
danielk197713adf8a2004-06-03 16:08:41 +00001554/*
drhf0119b22018-03-26 17:40:53 +00001555** Set a posix-advisory-lock.
1556**
1557** There are two versions of this routine. If compiled with
1558** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1559** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1560** value is set, then it is the number of milliseconds to wait before
1561** failing the lock. The iBusyTimeout value is always reset back to
1562** zero on each call.
1563**
1564** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1565** attempt to set the lock.
1566*/
1567#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1568# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1569#else
1570static int osSetPosixAdvisoryLock(
1571 int h, /* The file descriptor on which to take the lock */
1572 struct flock *pLock, /* The description of the lock */
1573 unixFile *pFile /* Structure holding timeout value */
1574){
dan7bb8b8a2020-05-06 20:27:18 +00001575 int tm = pFile->iBusyTimeout;
drhf0119b22018-03-26 17:40:53 +00001576 int rc = osFcntl(h,F_SETLK,pLock);
dan7bb8b8a2020-05-06 20:27:18 +00001577 while( rc<0 && tm>0 ){
drhf0119b22018-03-26 17:40:53 +00001578 /* On systems that support some kind of blocking file lock with a timeout,
1579 ** make appropriate changes here to invoke that blocking file lock. On
1580 ** generic posix, however, there is no such API. So we simply try the
1581 ** lock once every millisecond until either the timeout expires, or until
1582 ** the lock is obtained. */
drhddcfe922020-09-15 12:29:35 +00001583 unixSleep(0,1000);
drhfd725632018-03-26 20:43:05 +00001584 rc = osFcntl(h,F_SETLK,pLock);
dan7bb8b8a2020-05-06 20:27:18 +00001585 tm--;
drhf0119b22018-03-26 17:40:53 +00001586 }
1587 return rc;
1588}
1589#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1590
1591
1592/*
drha7e61d82011-03-12 17:02:57 +00001593** Attempt to set a system-lock on the file pFile. The lock is
1594** described by pLock.
1595**
drh77197112011-03-15 19:08:48 +00001596** If the pFile was opened read/write from unix-excl, then the only lock
1597** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001598** the first time any lock is attempted. All subsequent system locking
1599** operations become no-ops. Locking operations still happen internally,
1600** in order to coordinate access between separate database connections
1601** within this process, but all of that is handled in memory and the
1602** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001603**
1604** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1605** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1606** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001607**
1608** Zero is returned if the call completes successfully, or -1 if a call
1609** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001610*/
1611static int unixFileLock(unixFile *pFile, struct flock *pLock){
1612 int rc;
drh3cb93392011-03-12 18:10:44 +00001613 unixInodeInfo *pInode = pFile->pInode;
drh3cb93392011-03-12 18:10:44 +00001614 assert( pInode!=0 );
drhda6dc242018-07-23 21:10:37 +00001615 assert( sqlite3_mutex_held(pInode->pLockMutex) );
drh50358ad2015-12-02 01:04:33 +00001616 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001617 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001618 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001619 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001620 lock.l_whence = SEEK_SET;
1621 lock.l_start = SHARED_FIRST;
1622 lock.l_len = SHARED_SIZE;
1623 lock.l_type = F_WRLCK;
drhf0119b22018-03-26 17:40:53 +00001624 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
drha7e61d82011-03-12 17:02:57 +00001625 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001626 pInode->bProcessLock = 1;
1627 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001628 }else{
1629 rc = 0;
1630 }
1631 }else{
drhf0119b22018-03-26 17:40:53 +00001632 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
drha7e61d82011-03-12 17:02:57 +00001633 }
1634 return rc;
1635}
1636
1637/*
drh308c2a52010-05-14 11:30:18 +00001638** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001639** of the following:
1640**
drh2ac3ee92004-06-07 16:27:46 +00001641** (1) SHARED_LOCK
1642** (2) RESERVED_LOCK
1643** (3) PENDING_LOCK
1644** (4) EXCLUSIVE_LOCK
1645**
drhb3e04342004-06-08 00:47:47 +00001646** Sometimes when requesting one lock state, additional lock states
1647** are inserted in between. The locking might fail on one of the later
1648** transitions leaving the lock state different from what it started but
1649** still short of its goal. The following chart shows the allowed
1650** transitions and the inserted intermediate states:
1651**
1652** UNLOCKED -> SHARED
1653** SHARED -> RESERVED
1654** SHARED -> (PENDING) -> EXCLUSIVE
1655** RESERVED -> (PENDING) -> EXCLUSIVE
1656** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001657**
drha6abd042004-06-09 17:37:22 +00001658** This routine will only increase a lock. Use the sqlite3OsUnlock()
1659** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001660*/
drh308c2a52010-05-14 11:30:18 +00001661static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001662 /* The following describes the implementation of the various locks and
1663 ** lock transitions in terms of the POSIX advisory shared and exclusive
1664 ** lock primitives (called read-locks and write-locks below, to avoid
1665 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001666 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001667 ** accessing the same database file, in case that is ever required.
1668 **
1669 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1670 ** byte', each single bytes at well known offsets, and the 'shared byte
1671 ** range', a range of 510 bytes at a well known offset.
1672 **
1673 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001674 ** byte'. If this is successful, 'shared byte range' is read-locked
1675 ** and the lock on the 'pending byte' released. (Legacy note: When
1676 ** SQLite was first developed, Windows95 systems were still very common,
1677 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1678 ** single randomly selected by from the 'shared byte range' is locked.
1679 ** Windows95 is now pretty much extinct, but this work-around for the
1680 ** lack of shared-locks on Windows95 lives on, for backwards
1681 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001682 **
danielk197790ba3bd2004-06-25 08:32:25 +00001683 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1684 ** A RESERVED lock is implemented by grabbing a write-lock on the
1685 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001686 **
1687 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001688 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1689 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1690 ** obtained, but existing SHARED locks are allowed to persist. A process
1691 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1692 ** This property is used by the algorithm for rolling back a journal file
1693 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001694 **
danielk197790ba3bd2004-06-25 08:32:25 +00001695 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1696 ** implemented by obtaining a write-lock on the entire 'shared byte
1697 ** range'. Since all other locks require a read-lock on one of the bytes
1698 ** within this range, this ensures that no other locks are held on the
1699 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001700 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001701 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001702 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001703 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001704 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001705 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001706
drh054889e2005-11-30 03:20:31 +00001707 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001708 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1709 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001710 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001711 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001712
1713 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001714 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001715 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001716 */
drh308c2a52010-05-14 11:30:18 +00001717 if( pFile->eFileLock>=eFileLock ){
1718 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1719 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001720 return SQLITE_OK;
1721 }
1722
drh0c2694b2009-09-03 16:23:44 +00001723 /* Make sure the locking sequence is correct.
1724 ** (1) We never move from unlocked to anything higher than shared lock.
1725 ** (2) SQLite never explicitly requests a pendig lock.
1726 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001727 */
drh308c2a52010-05-14 11:30:18 +00001728 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1729 assert( eFileLock!=PENDING_LOCK );
1730 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001731
drh8af6c222010-05-14 12:43:01 +00001732 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001733 */
drh8af6c222010-05-14 12:43:01 +00001734 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001735 sqlite3_mutex_enter(pInode->pLockMutex);
drh029b44b2006-01-15 00:13:15 +00001736
danielk1977ad94b582007-08-20 06:44:22 +00001737 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001738 ** handle that precludes the requested lock, return BUSY.
1739 */
drh8af6c222010-05-14 12:43:01 +00001740 if( (pFile->eFileLock!=pInode->eFileLock &&
1741 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001742 ){
1743 rc = SQLITE_BUSY;
1744 goto end_lock;
1745 }
1746
1747 /* If a SHARED lock is requested, and some thread using this PID already
1748 ** has a SHARED or RESERVED lock, then increment reference counts and
1749 ** return SQLITE_OK.
1750 */
drh308c2a52010-05-14 11:30:18 +00001751 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001752 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001753 assert( eFileLock==SHARED_LOCK );
1754 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001755 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001756 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001757 pInode->nShared++;
1758 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001759 goto end_lock;
1760 }
1761
danielk19779a1d0ab2004-06-01 14:09:28 +00001762
drh3cde3bb2004-06-12 02:17:14 +00001763 /* A PENDING lock is needed before acquiring a SHARED lock and before
1764 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1765 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001766 */
drh0c2694b2009-09-03 16:23:44 +00001767 lock.l_len = 1L;
1768 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001769 if( eFileLock==SHARED_LOCK
1770 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001771 ){
drh308c2a52010-05-14 11:30:18 +00001772 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001773 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001774 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001775 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001776 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001777 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001778 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001779 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001780 goto end_lock;
1781 }
drh3cde3bb2004-06-12 02:17:14 +00001782 }
1783
1784
1785 /* If control gets to this point, then actually go ahead and make
1786 ** operating system calls for the specified lock.
1787 */
drh308c2a52010-05-14 11:30:18 +00001788 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001789 assert( pInode->nShared==0 );
1790 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001791 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001792
drh2ac3ee92004-06-07 16:27:46 +00001793 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001794 lock.l_start = SHARED_FIRST;
1795 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001796 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001797 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001798 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001799 }
dan661d71a2011-03-30 19:08:03 +00001800
drh2ac3ee92004-06-07 16:27:46 +00001801 /* Drop the temporary PENDING lock */
1802 lock.l_start = PENDING_BYTE;
1803 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001804 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001805 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1806 /* This could happen with a network mount */
1807 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001808 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001809 }
dan661d71a2011-03-30 19:08:03 +00001810
1811 if( rc ){
1812 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001813 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001814 }
dan661d71a2011-03-30 19:08:03 +00001815 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001816 }else{
drh308c2a52010-05-14 11:30:18 +00001817 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001818 pInode->nLock++;
1819 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001820 }
drh8af6c222010-05-14 12:43:01 +00001821 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001822 /* We are trying for an exclusive lock but another thread in this
1823 ** same process is still holding a shared lock. */
1824 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001825 }else{
drh3cde3bb2004-06-12 02:17:14 +00001826 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001827 ** assumed that there is a SHARED or greater lock on the file
1828 ** already.
1829 */
drh308c2a52010-05-14 11:30:18 +00001830 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001831 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001832
1833 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1834 if( eFileLock==RESERVED_LOCK ){
1835 lock.l_start = RESERVED_BYTE;
1836 lock.l_len = 1L;
1837 }else{
1838 lock.l_start = SHARED_FIRST;
1839 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001840 }
dan661d71a2011-03-30 19:08:03 +00001841
1842 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001843 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001844 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001845 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001846 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001847 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001848 }
drhbbd42a62004-05-22 17:41:58 +00001849 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001850
drh8f941bc2009-01-14 23:03:40 +00001851
drhd3d8c042012-05-29 17:02:40 +00001852#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001853 /* Set up the transaction-counter change checking flags when
1854 ** transitioning from a SHARED to a RESERVED lock. The change
1855 ** from SHARED to RESERVED marks the beginning of a normal
1856 ** write operation (not a hot journal rollback).
1857 */
1858 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001859 && pFile->eFileLock<=SHARED_LOCK
1860 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001861 ){
1862 pFile->transCntrChng = 0;
1863 pFile->dbUpdate = 0;
1864 pFile->inNormalWrite = 1;
1865 }
1866#endif
1867
1868
danielk1977ecb2a962004-06-02 06:30:16 +00001869 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001870 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001871 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001872 }else if( eFileLock==EXCLUSIVE_LOCK ){
1873 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001874 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001875 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001876
1877end_lock:
drhda6dc242018-07-23 21:10:37 +00001878 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001879 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1880 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001881 return rc;
1882}
1883
1884/*
dan08da86a2009-08-21 17:18:03 +00001885** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001886** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001887*/
1888static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001889 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001890 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drhef52b362018-08-13 22:50:34 +00001891 assert( unixFileMutexHeld(pFile) );
drh8af6c222010-05-14 12:43:01 +00001892 p->pNext = pInode->pUnused;
1893 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001894 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001895 pFile->pPreallocatedUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001896}
1897
1898/*
drh308c2a52010-05-14 11:30:18 +00001899** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001900** must be either NO_LOCK or SHARED_LOCK.
1901**
1902** If the locking level of the file descriptor is already at or below
1903** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001904**
1905** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1906** the byte range is divided into 2 parts and the first part is unlocked then
1907** set to a read lock, then the other part is simply unlocked. This works
1908** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1909** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001910*/
drha7e61d82011-03-12 17:02:57 +00001911static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001912 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001913 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001914 struct flock lock;
1915 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001916
drh054889e2005-11-30 03:20:31 +00001917 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001918 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001919 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001920 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001921
drh308c2a52010-05-14 11:30:18 +00001922 assert( eFileLock<=SHARED_LOCK );
1923 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001924 return SQLITE_OK;
1925 }
drh8af6c222010-05-14 12:43:01 +00001926 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001927 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001928 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001929 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001930 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001931
drhd3d8c042012-05-29 17:02:40 +00001932#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001933 /* When reducing a lock such that other processes can start
1934 ** reading the database file again, make sure that the
1935 ** transaction counter was updated if any part of the database
1936 ** file changed. If the transaction counter is not updated,
1937 ** other connections to the same file might not realize that
1938 ** the file has changed and hence might not know to flush their
1939 ** cache. The use of a stale cache can lead to database corruption.
1940 */
drh8f941bc2009-01-14 23:03:40 +00001941 pFile->inNormalWrite = 0;
1942#endif
1943
drh7ed97b92010-01-20 13:07:21 +00001944 /* downgrading to a shared lock on NFS involves clearing the write lock
1945 ** before establishing the readlock - to avoid a race condition we downgrade
1946 ** the lock in 2 blocks, so that part of the range will be covered by a
1947 ** write lock until the rest is covered by a read lock:
1948 ** 1: [WWWWW]
1949 ** 2: [....W]
1950 ** 3: [RRRRW]
1951 ** 4: [RRRR.]
1952 */
drh308c2a52010-05-14 11:30:18 +00001953 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001954#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001955 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001956 assert( handleNFSUnlock==0 );
1957#endif
1958#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001959 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001960 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001961 off_t divSize = SHARED_SIZE - 1;
1962
1963 lock.l_type = F_UNLCK;
1964 lock.l_whence = SEEK_SET;
1965 lock.l_start = SHARED_FIRST;
1966 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001967 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001968 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001969 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001970 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001971 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001972 }
drh7ed97b92010-01-20 13:07:21 +00001973 lock.l_type = F_RDLCK;
1974 lock.l_whence = SEEK_SET;
1975 lock.l_start = SHARED_FIRST;
1976 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001977 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001978 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001979 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1980 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001981 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001982 }
1983 goto end_unlock;
1984 }
1985 lock.l_type = F_UNLCK;
1986 lock.l_whence = SEEK_SET;
1987 lock.l_start = SHARED_FIRST+divSize;
1988 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001989 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001990 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001991 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001992 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001993 goto end_unlock;
1994 }
drh30f776f2011-02-25 03:25:07 +00001995 }else
1996#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1997 {
drh7ed97b92010-01-20 13:07:21 +00001998 lock.l_type = F_RDLCK;
1999 lock.l_whence = SEEK_SET;
2000 lock.l_start = SHARED_FIRST;
2001 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00002002 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00002003 /* In theory, the call to unixFileLock() cannot fail because another
2004 ** process is holding an incompatible lock. If it does, this
2005 ** indicates that the other process is not following the locking
2006 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
2007 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2008 ** an assert to fail). */
2009 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002010 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00002011 goto end_unlock;
2012 }
drh9c105bb2004-10-02 20:38:28 +00002013 }
2014 }
drhbbd42a62004-05-22 17:41:58 +00002015 lock.l_type = F_UNLCK;
2016 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00002017 lock.l_start = PENDING_BYTE;
2018 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00002019 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002020 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002021 }else{
danea83bc62011-04-01 11:56:32 +00002022 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002023 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00002024 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00002025 }
drhbbd42a62004-05-22 17:41:58 +00002026 }
drh308c2a52010-05-14 11:30:18 +00002027 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00002028 /* Decrement the shared lock counter. Release the lock using an
2029 ** OS call only when all threads in this same process have released
2030 ** the lock.
2031 */
drh8af6c222010-05-14 12:43:01 +00002032 pInode->nShared--;
2033 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00002034 lock.l_type = F_UNLCK;
2035 lock.l_whence = SEEK_SET;
2036 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00002037 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002038 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002039 }else{
danea83bc62011-04-01 11:56:32 +00002040 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002041 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00002042 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002043 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002044 }
drha6abd042004-06-09 17:37:22 +00002045 }
2046
drhbbd42a62004-05-22 17:41:58 +00002047 /* Decrement the count of locks against this same file. When the
2048 ** count reaches zero, close any other file descriptors whose close
2049 ** was deferred because of outstanding locks.
2050 */
drh8af6c222010-05-14 12:43:01 +00002051 pInode->nLock--;
2052 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00002053 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00002054 }
drhf2f105d2012-08-20 15:53:54 +00002055
aswift5b1a2562008-08-22 00:22:35 +00002056end_unlock:
drhda6dc242018-07-23 21:10:37 +00002057 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00002058 if( rc==SQLITE_OK ){
2059 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00002060 }
drh9c105bb2004-10-02 20:38:28 +00002061 return rc;
drhbbd42a62004-05-22 17:41:58 +00002062}
2063
2064/*
drh308c2a52010-05-14 11:30:18 +00002065** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002066** must be either NO_LOCK or SHARED_LOCK.
2067**
2068** If the locking level of the file descriptor is already at or below
2069** the requested locking level, this routine is a no-op.
2070*/
drh308c2a52010-05-14 11:30:18 +00002071static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00002072#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00002073 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00002074#endif
drha7e61d82011-03-12 17:02:57 +00002075 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00002076}
2077
mistachkine98844f2013-08-24 00:59:24 +00002078#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002079static int unixMapfile(unixFile *pFd, i64 nByte);
2080static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00002081#endif
danf23da962013-03-23 21:00:41 +00002082
drh7ed97b92010-01-20 13:07:21 +00002083/*
danielk1977e339d652008-06-28 11:23:00 +00002084** This function performs the parts of the "close file" operation
2085** common to all locking schemes. It closes the directory and file
2086** handles, if they are valid, and sets all fields of the unixFile
2087** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00002088**
2089** It is *not* necessary to hold the mutex when this routine is called,
2090** even on VxWorks. A mutex will be acquired on VxWorks by the
2091** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00002092*/
2093static int closeUnixFile(sqlite3_file *id){
2094 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00002095#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002096 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00002097#endif
dan661d71a2011-03-30 19:08:03 +00002098 if( pFile->h>=0 ){
2099 robust_close(pFile, pFile->h, __LINE__);
2100 pFile->h = -1;
2101 }
2102#if OS_VXWORKS
2103 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00002104 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00002105 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00002106 }
2107 vxworksReleaseFileId(pFile->pId);
2108 pFile->pId = 0;
2109 }
2110#endif
drh0bdbc902014-06-16 18:35:06 +00002111#ifdef SQLITE_UNLINK_AFTER_CLOSE
2112 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2113 osUnlink(pFile->zPath);
2114 sqlite3_free(*(char**)&pFile->zPath);
2115 pFile->zPath = 0;
2116 }
2117#endif
dan661d71a2011-03-30 19:08:03 +00002118 OSTRACE(("CLOSE %-3d\n", pFile->h));
2119 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00002120 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00002121 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00002122 return SQLITE_OK;
2123}
2124
2125/*
danielk1977e3026632004-06-22 11:29:02 +00002126** Close a file.
2127*/
danielk197762079062007-08-15 17:08:46 +00002128static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002129 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002130 unixFile *pFile = (unixFile *)id;
drhef52b362018-08-13 22:50:34 +00002131 unixInodeInfo *pInode = pFile->pInode;
2132
2133 assert( pInode!=0 );
drhfbc7e882013-04-11 01:16:15 +00002134 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002135 unixUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00002136 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00002137 unixEnterMutex();
2138
2139 /* unixFile.pInode is always valid here. Otherwise, a different close
2140 ** routine (e.g. nolockClose()) would be called instead.
2141 */
2142 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
drhef52b362018-08-13 22:50:34 +00002143 sqlite3_mutex_enter(pInode->pLockMutex);
drh3fcef1a2018-08-16 16:24:24 +00002144 if( pInode->nLock ){
dan661d71a2011-03-30 19:08:03 +00002145 /* If there are outstanding locks, do not actually close the file just
2146 ** yet because that would clear those locks. Instead, add the file
2147 ** descriptor to pInode->pUnused list. It will be automatically closed
2148 ** when the last lock is cleared.
2149 */
2150 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002151 }
drhef52b362018-08-13 22:50:34 +00002152 sqlite3_mutex_leave(pInode->pLockMutex);
dan661d71a2011-03-30 19:08:03 +00002153 releaseInodeInfo(pFile);
dan2b06b072020-09-04 17:30:59 +00002154 assert( pFile->pShm==0 );
dan661d71a2011-03-30 19:08:03 +00002155 rc = closeUnixFile(id);
2156 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002157 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002158}
2159
drh734c9862008-11-28 15:37:20 +00002160/************** End of the posix advisory lock implementation *****************
2161******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002162
drh734c9862008-11-28 15:37:20 +00002163/******************************************************************************
2164****************************** No-op Locking **********************************
2165**
2166** Of the various locking implementations available, this is by far the
2167** simplest: locking is ignored. No attempt is made to lock the database
2168** file for reading or writing.
2169**
2170** This locking mode is appropriate for use on read-only databases
2171** (ex: databases that are burned into CD-ROM, for example.) It can
2172** also be used if the application employs some external mechanism to
2173** prevent simultaneous access of the same database by two or more
2174** database connections. But there is a serious risk of database
2175** corruption if this locking mode is used in situations where multiple
2176** database connections are accessing the same database file at the same
2177** time and one or more of those connections are writing.
2178*/
drhbfe66312006-10-03 17:40:40 +00002179
drh734c9862008-11-28 15:37:20 +00002180static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2181 UNUSED_PARAMETER(NotUsed);
2182 *pResOut = 0;
2183 return SQLITE_OK;
2184}
drh734c9862008-11-28 15:37:20 +00002185static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2186 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2187 return SQLITE_OK;
2188}
drh734c9862008-11-28 15:37:20 +00002189static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2190 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2191 return SQLITE_OK;
2192}
2193
2194/*
drh9b35ea62008-11-29 02:20:26 +00002195** Close the file.
drh734c9862008-11-28 15:37:20 +00002196*/
2197static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002198 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002199}
2200
2201/******************* End of the no-op lock implementation *********************
2202******************************************************************************/
2203
2204/******************************************************************************
2205************************* Begin dot-file Locking ******************************
2206**
mistachkin48864df2013-03-21 21:20:32 +00002207** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002208** files (really a directory) to control access to the database. This works
2209** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002210**
2211** (1) There is zero concurrency. A single reader blocks all other
2212** connections from reading or writing the database.
2213**
2214** (2) An application crash or power loss can leave stale lock files
2215** sitting around that need to be cleared manually.
2216**
2217** Nevertheless, a dotlock is an appropriate locking mode for use if no
2218** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002219**
drh9ef6bc42011-11-04 02:24:02 +00002220** Dotfile locking works by creating a subdirectory in the same directory as
2221** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002222** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002223** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002224*/
2225
2226/*
2227** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002228** lock directory.
drh734c9862008-11-28 15:37:20 +00002229*/
2230#define DOTLOCK_SUFFIX ".lock"
2231
drh7708e972008-11-29 00:56:52 +00002232/*
2233** This routine checks if there is a RESERVED lock held on the specified
2234** file by this or any other process. If such a lock is held, set *pResOut
2235** to a non-zero value otherwise *pResOut is set to zero. The return value
2236** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2237**
2238** In dotfile locking, either a lock exists or it does not. So in this
2239** variation of CheckReservedLock(), *pResOut is set to true if any lock
2240** is held on the file and false if the file is unlocked.
2241*/
drh734c9862008-11-28 15:37:20 +00002242static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2243 int rc = SQLITE_OK;
2244 int reserved = 0;
2245 unixFile *pFile = (unixFile*)id;
2246
2247 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2248
2249 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002250 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002251 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002252 *pResOut = reserved;
2253 return rc;
2254}
2255
drh7708e972008-11-29 00:56:52 +00002256/*
drh308c2a52010-05-14 11:30:18 +00002257** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002258** of the following:
2259**
2260** (1) SHARED_LOCK
2261** (2) RESERVED_LOCK
2262** (3) PENDING_LOCK
2263** (4) EXCLUSIVE_LOCK
2264**
2265** Sometimes when requesting one lock state, additional lock states
2266** are inserted in between. The locking might fail on one of the later
2267** transitions leaving the lock state different from what it started but
2268** still short of its goal. The following chart shows the allowed
2269** transitions and the inserted intermediate states:
2270**
2271** UNLOCKED -> SHARED
2272** SHARED -> RESERVED
2273** SHARED -> (PENDING) -> EXCLUSIVE
2274** RESERVED -> (PENDING) -> EXCLUSIVE
2275** PENDING -> EXCLUSIVE
2276**
2277** This routine will only increase a lock. Use the sqlite3OsUnlock()
2278** routine to lower a locking level.
2279**
2280** With dotfile locking, we really only support state (4): EXCLUSIVE.
2281** But we track the other locking levels internally.
2282*/
drh308c2a52010-05-14 11:30:18 +00002283static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002284 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002285 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002286 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002287
drh7708e972008-11-29 00:56:52 +00002288
2289 /* If we have any lock, then the lock file already exists. All we have
2290 ** to do is adjust our internal record of the lock level.
2291 */
drh308c2a52010-05-14 11:30:18 +00002292 if( pFile->eFileLock > NO_LOCK ){
2293 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002294 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002295#ifdef HAVE_UTIME
2296 utime(zLockFile, NULL);
2297#else
drh734c9862008-11-28 15:37:20 +00002298 utimes(zLockFile, NULL);
2299#endif
drh7708e972008-11-29 00:56:52 +00002300 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002301 }
2302
2303 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002304 rc = osMkdir(zLockFile, 0777);
2305 if( rc<0 ){
2306 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002307 int tErrno = errno;
2308 if( EEXIST == tErrno ){
2309 rc = SQLITE_BUSY;
2310 } else {
2311 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002312 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002313 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002314 }
2315 }
drh7708e972008-11-29 00:56:52 +00002316 return rc;
drh734c9862008-11-28 15:37:20 +00002317 }
drh734c9862008-11-28 15:37:20 +00002318
2319 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002320 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002321 return rc;
2322}
2323
drh7708e972008-11-29 00:56:52 +00002324/*
drh308c2a52010-05-14 11:30:18 +00002325** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002326** must be either NO_LOCK or SHARED_LOCK.
2327**
2328** If the locking level of the file descriptor is already at or below
2329** the requested locking level, this routine is a no-op.
2330**
2331** When the locking level reaches NO_LOCK, delete the lock file.
2332*/
drh308c2a52010-05-14 11:30:18 +00002333static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002334 unixFile *pFile = (unixFile*)id;
2335 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002336 int rc;
drh734c9862008-11-28 15:37:20 +00002337
2338 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002339 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002340 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002341 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002342
2343 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002344 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002345 return SQLITE_OK;
2346 }
drh7708e972008-11-29 00:56:52 +00002347
2348 /* To downgrade to shared, simply update our internal notion of the
2349 ** lock state. No need to mess with the file on disk.
2350 */
drh308c2a52010-05-14 11:30:18 +00002351 if( eFileLock==SHARED_LOCK ){
2352 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002353 return SQLITE_OK;
2354 }
2355
drh7708e972008-11-29 00:56:52 +00002356 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002357 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002358 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002359 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002360 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002361 if( tErrno==ENOENT ){
2362 rc = SQLITE_OK;
2363 }else{
danea83bc62011-04-01 11:56:32 +00002364 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002365 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002366 }
2367 return rc;
2368 }
drh308c2a52010-05-14 11:30:18 +00002369 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002370 return SQLITE_OK;
2371}
2372
2373/*
drh9b35ea62008-11-29 02:20:26 +00002374** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002375*/
2376static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002377 unixFile *pFile = (unixFile*)id;
2378 assert( id!=0 );
2379 dotlockUnlock(id, NO_LOCK);
2380 sqlite3_free(pFile->lockingContext);
2381 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002382}
2383/****************** End of the dot-file lock implementation *******************
2384******************************************************************************/
2385
2386/******************************************************************************
2387************************** Begin flock Locking ********************************
2388**
2389** Use the flock() system call to do file locking.
2390**
drh6b9d6dd2008-12-03 19:34:47 +00002391** flock() locking is like dot-file locking in that the various
2392** fine-grain locking levels supported by SQLite are collapsed into
2393** a single exclusive lock. In other words, SHARED, RESERVED, and
2394** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2395** still works when you do this, but concurrency is reduced since
2396** only a single process can be reading the database at a time.
2397**
drhe89b2912015-03-03 20:42:01 +00002398** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002399*/
drhe89b2912015-03-03 20:42:01 +00002400#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002401
drh6b9d6dd2008-12-03 19:34:47 +00002402/*
drhff812312011-02-23 13:33:46 +00002403** Retry flock() calls that fail with EINTR
2404*/
2405#ifdef EINTR
2406static int robust_flock(int fd, int op){
2407 int rc;
2408 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2409 return rc;
2410}
2411#else
drh5c819272011-02-23 14:00:12 +00002412# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002413#endif
2414
2415
2416/*
drh6b9d6dd2008-12-03 19:34:47 +00002417** This routine checks if there is a RESERVED lock held on the specified
2418** file by this or any other process. If such a lock is held, set *pResOut
2419** to a non-zero value otherwise *pResOut is set to zero. The return value
2420** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2421*/
drh734c9862008-11-28 15:37:20 +00002422static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2423 int rc = SQLITE_OK;
2424 int reserved = 0;
2425 unixFile *pFile = (unixFile*)id;
2426
2427 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2428
2429 assert( pFile );
2430
2431 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002432 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002433 reserved = 1;
2434 }
2435
2436 /* Otherwise see if some other process holds it. */
2437 if( !reserved ){
2438 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002439 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002440 if( !lrc ){
2441 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002442 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002443 if ( lrc ) {
2444 int tErrno = errno;
2445 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002446 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002447 storeLastErrno(pFile, tErrno);
2448 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002449 }
2450 } else {
2451 int tErrno = errno;
2452 reserved = 1;
2453 /* someone else might have it reserved */
2454 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2455 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002456 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002457 rc = lrc;
2458 }
2459 }
2460 }
drh308c2a52010-05-14 11:30:18 +00002461 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002462
2463#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002464 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002465 rc = SQLITE_OK;
2466 reserved=1;
2467 }
2468#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2469 *pResOut = reserved;
2470 return rc;
2471}
2472
drh6b9d6dd2008-12-03 19:34:47 +00002473/*
drh308c2a52010-05-14 11:30:18 +00002474** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002475** of the following:
2476**
2477** (1) SHARED_LOCK
2478** (2) RESERVED_LOCK
2479** (3) PENDING_LOCK
2480** (4) EXCLUSIVE_LOCK
2481**
2482** Sometimes when requesting one lock state, additional lock states
2483** are inserted in between. The locking might fail on one of the later
2484** transitions leaving the lock state different from what it started but
2485** still short of its goal. The following chart shows the allowed
2486** transitions and the inserted intermediate states:
2487**
2488** UNLOCKED -> SHARED
2489** SHARED -> RESERVED
2490** SHARED -> (PENDING) -> EXCLUSIVE
2491** RESERVED -> (PENDING) -> EXCLUSIVE
2492** PENDING -> EXCLUSIVE
2493**
2494** flock() only really support EXCLUSIVE locks. We track intermediate
2495** lock states in the sqlite3_file structure, but all locks SHARED or
2496** above are really EXCLUSIVE locks and exclude all other processes from
2497** access the file.
2498**
2499** This routine will only increase a lock. Use the sqlite3OsUnlock()
2500** routine to lower a locking level.
2501*/
drh308c2a52010-05-14 11:30:18 +00002502static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002503 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002504 unixFile *pFile = (unixFile*)id;
2505
2506 assert( pFile );
2507
2508 /* if we already have a lock, it is exclusive.
2509 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002510 if (pFile->eFileLock > NO_LOCK) {
2511 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002512 return SQLITE_OK;
2513 }
2514
2515 /* grab an exclusive lock */
2516
drhff812312011-02-23 13:33:46 +00002517 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002518 int tErrno = errno;
2519 /* didn't get, must be busy */
2520 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2521 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002522 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002523 }
2524 } else {
2525 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002526 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002527 }
drh308c2a52010-05-14 11:30:18 +00002528 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2529 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002530#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002531 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002532 rc = SQLITE_BUSY;
2533 }
2534#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2535 return rc;
2536}
2537
drh6b9d6dd2008-12-03 19:34:47 +00002538
2539/*
drh308c2a52010-05-14 11:30:18 +00002540** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002541** must be either NO_LOCK or SHARED_LOCK.
2542**
2543** If the locking level of the file descriptor is already at or below
2544** the requested locking level, this routine is a no-op.
2545*/
drh308c2a52010-05-14 11:30:18 +00002546static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002547 unixFile *pFile = (unixFile*)id;
2548
2549 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002550 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002551 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002552 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002553
2554 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002555 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002556 return SQLITE_OK;
2557 }
2558
2559 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002560 if (eFileLock==SHARED_LOCK) {
2561 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002562 return SQLITE_OK;
2563 }
2564
2565 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002566 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002567#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002568 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002569#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002570 return SQLITE_IOERR_UNLOCK;
2571 }else{
drh308c2a52010-05-14 11:30:18 +00002572 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002573 return SQLITE_OK;
2574 }
2575}
2576
2577/*
2578** Close a file.
2579*/
2580static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002581 assert( id!=0 );
2582 flockUnlock(id, NO_LOCK);
2583 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002584}
2585
2586#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2587
2588/******************* End of the flock lock implementation *********************
2589******************************************************************************/
2590
2591/******************************************************************************
2592************************ Begin Named Semaphore Locking ************************
2593**
2594** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002595**
2596** Semaphore locking is like dot-lock and flock in that it really only
2597** supports EXCLUSIVE locking. Only a single process can read or write
2598** the database file at a time. This reduces potential concurrency, but
2599** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002600*/
2601#if OS_VXWORKS
2602
drh6b9d6dd2008-12-03 19:34:47 +00002603/*
2604** This routine checks if there is a RESERVED lock held on the specified
2605** file by this or any other process. If such a lock is held, set *pResOut
2606** to a non-zero value otherwise *pResOut is set to zero. The return value
2607** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2608*/
drh8cd5b252015-03-02 22:06:43 +00002609static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002610 int rc = SQLITE_OK;
2611 int reserved = 0;
2612 unixFile *pFile = (unixFile*)id;
2613
2614 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2615
2616 assert( pFile );
2617
2618 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002619 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002620 reserved = 1;
2621 }
2622
2623 /* Otherwise see if some other process holds it. */
2624 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002625 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002626
2627 if( sem_trywait(pSem)==-1 ){
2628 int tErrno = errno;
2629 if( EAGAIN != tErrno ){
2630 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002631 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002632 } else {
2633 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002634 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002635 }
2636 }else{
2637 /* we could have it if we want it */
2638 sem_post(pSem);
2639 }
2640 }
drh308c2a52010-05-14 11:30:18 +00002641 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002642
2643 *pResOut = reserved;
2644 return rc;
2645}
2646
drh6b9d6dd2008-12-03 19:34:47 +00002647/*
drh308c2a52010-05-14 11:30:18 +00002648** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002649** of the following:
2650**
2651** (1) SHARED_LOCK
2652** (2) RESERVED_LOCK
2653** (3) PENDING_LOCK
2654** (4) EXCLUSIVE_LOCK
2655**
2656** Sometimes when requesting one lock state, additional lock states
2657** are inserted in between. The locking might fail on one of the later
2658** transitions leaving the lock state different from what it started but
2659** still short of its goal. The following chart shows the allowed
2660** transitions and the inserted intermediate states:
2661**
2662** UNLOCKED -> SHARED
2663** SHARED -> RESERVED
2664** SHARED -> (PENDING) -> EXCLUSIVE
2665** RESERVED -> (PENDING) -> EXCLUSIVE
2666** PENDING -> EXCLUSIVE
2667**
2668** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2669** lock states in the sqlite3_file structure, but all locks SHARED or
2670** above are really EXCLUSIVE locks and exclude all other processes from
2671** access the file.
2672**
2673** This routine will only increase a lock. Use the sqlite3OsUnlock()
2674** routine to lower a locking level.
2675*/
drh8cd5b252015-03-02 22:06:43 +00002676static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002677 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002678 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002679 int rc = SQLITE_OK;
2680
2681 /* if we already have a lock, it is exclusive.
2682 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002683 if (pFile->eFileLock > NO_LOCK) {
2684 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002685 rc = SQLITE_OK;
2686 goto sem_end_lock;
2687 }
2688
2689 /* lock semaphore now but bail out when already locked. */
2690 if( sem_trywait(pSem)==-1 ){
2691 rc = SQLITE_BUSY;
2692 goto sem_end_lock;
2693 }
2694
2695 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002696 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002697
2698 sem_end_lock:
2699 return rc;
2700}
2701
drh6b9d6dd2008-12-03 19:34:47 +00002702/*
drh308c2a52010-05-14 11:30:18 +00002703** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002704** must be either NO_LOCK or SHARED_LOCK.
2705**
2706** If the locking level of the file descriptor is already at or below
2707** the requested locking level, this routine is a no-op.
2708*/
drh8cd5b252015-03-02 22:06:43 +00002709static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002710 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002711 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002712
2713 assert( pFile );
2714 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002715 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002716 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002717 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002718
2719 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002720 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002721 return SQLITE_OK;
2722 }
2723
2724 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002725 if (eFileLock==SHARED_LOCK) {
2726 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002727 return SQLITE_OK;
2728 }
2729
2730 /* no, really unlock. */
2731 if ( sem_post(pSem)==-1 ) {
2732 int rc, tErrno = errno;
2733 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2734 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002735 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002736 }
2737 return rc;
2738 }
drh308c2a52010-05-14 11:30:18 +00002739 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002740 return SQLITE_OK;
2741}
2742
2743/*
2744 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002745 */
drh8cd5b252015-03-02 22:06:43 +00002746static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002747 if( id ){
2748 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002749 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002750 assert( pFile );
drh095908e2018-08-13 20:46:18 +00002751 assert( unixFileMutexNotheld(pFile) );
drh734c9862008-11-28 15:37:20 +00002752 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002753 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002754 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002755 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002756 }
2757 return SQLITE_OK;
2758}
2759
2760#endif /* OS_VXWORKS */
2761/*
2762** Named semaphore locking is only available on VxWorks.
2763**
2764*************** End of the named semaphore lock implementation ****************
2765******************************************************************************/
2766
2767
2768/******************************************************************************
2769*************************** Begin AFP Locking *********************************
2770**
2771** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2772** on Apple Macintosh computers - both OS9 and OSX.
2773**
2774** Third-party implementations of AFP are available. But this code here
2775** only works on OSX.
2776*/
2777
drhd2cb50b2009-01-09 21:41:17 +00002778#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002779/*
2780** The afpLockingContext structure contains all afp lock specific state
2781*/
drhbfe66312006-10-03 17:40:40 +00002782typedef struct afpLockingContext afpLockingContext;
2783struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002784 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002785 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002786};
2787
2788struct ByteRangeLockPB2
2789{
2790 unsigned long long offset; /* offset to first byte to lock */
2791 unsigned long long length; /* nbr of bytes to lock */
2792 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2793 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2794 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2795 int fd; /* file desc to assoc this lock with */
2796};
2797
drhfd131da2007-08-07 17:13:03 +00002798#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002799
drh6b9d6dd2008-12-03 19:34:47 +00002800/*
2801** This is a utility for setting or clearing a bit-range lock on an
2802** AFP filesystem.
2803**
2804** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2805*/
2806static int afpSetLock(
2807 const char *path, /* Name of the file to be locked or unlocked */
2808 unixFile *pFile, /* Open file descriptor on path */
2809 unsigned long long offset, /* First byte to be locked */
2810 unsigned long long length, /* Number of bytes to lock */
2811 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002812){
drh6b9d6dd2008-12-03 19:34:47 +00002813 struct ByteRangeLockPB2 pb;
2814 int err;
drhbfe66312006-10-03 17:40:40 +00002815
2816 pb.unLockFlag = setLockFlag ? 0 : 1;
2817 pb.startEndFlag = 0;
2818 pb.offset = offset;
2819 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002820 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002821
drh308c2a52010-05-14 11:30:18 +00002822 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002823 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002824 offset, length));
drhbfe66312006-10-03 17:40:40 +00002825 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2826 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002827 int rc;
2828 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002829 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2830 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002831#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2832 rc = SQLITE_BUSY;
2833#else
drh734c9862008-11-28 15:37:20 +00002834 rc = sqliteErrorFromPosixError(tErrno,
2835 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002836#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002837 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002838 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002839 }
2840 return rc;
drhbfe66312006-10-03 17:40:40 +00002841 } else {
aswift5b1a2562008-08-22 00:22:35 +00002842 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002843 }
2844}
2845
drh6b9d6dd2008-12-03 19:34:47 +00002846/*
2847** This routine checks if there is a RESERVED lock held on the specified
2848** file by this or any other process. If such a lock is held, set *pResOut
2849** to a non-zero value otherwise *pResOut is set to zero. The return value
2850** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2851*/
danielk1977e339d652008-06-28 11:23:00 +00002852static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002853 int rc = SQLITE_OK;
2854 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002855 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002856 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002857
aswift5b1a2562008-08-22 00:22:35 +00002858 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2859
2860 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002861 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002862 if( context->reserved ){
2863 *pResOut = 1;
2864 return SQLITE_OK;
2865 }
drhda6dc242018-07-23 21:10:37 +00002866 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
drhbfe66312006-10-03 17:40:40 +00002867 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002868 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002869 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002870 }
2871
2872 /* Otherwise see if some other process holds it.
2873 */
aswift5b1a2562008-08-22 00:22:35 +00002874 if( !reserved ){
2875 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002876 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002877 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002878 /* if we succeeded in taking the reserved lock, unlock it to restore
2879 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002880 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002881 } else {
2882 /* if we failed to get the lock then someone else must have it */
2883 reserved = 1;
2884 }
2885 if( IS_LOCK_ERROR(lrc) ){
2886 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002887 }
2888 }
drhbfe66312006-10-03 17:40:40 +00002889
drhda6dc242018-07-23 21:10:37 +00002890 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00002891 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002892
2893 *pResOut = reserved;
2894 return rc;
drhbfe66312006-10-03 17:40:40 +00002895}
2896
drh6b9d6dd2008-12-03 19:34:47 +00002897/*
drh308c2a52010-05-14 11:30:18 +00002898** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002899** of the following:
2900**
2901** (1) SHARED_LOCK
2902** (2) RESERVED_LOCK
2903** (3) PENDING_LOCK
2904** (4) EXCLUSIVE_LOCK
2905**
2906** Sometimes when requesting one lock state, additional lock states
2907** are inserted in between. The locking might fail on one of the later
2908** transitions leaving the lock state different from what it started but
2909** still short of its goal. The following chart shows the allowed
2910** transitions and the inserted intermediate states:
2911**
2912** UNLOCKED -> SHARED
2913** SHARED -> RESERVED
2914** SHARED -> (PENDING) -> EXCLUSIVE
2915** RESERVED -> (PENDING) -> EXCLUSIVE
2916** PENDING -> EXCLUSIVE
2917**
2918** This routine will only increase a lock. Use the sqlite3OsUnlock()
2919** routine to lower a locking level.
2920*/
drh308c2a52010-05-14 11:30:18 +00002921static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002922 int rc = SQLITE_OK;
2923 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002924 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002925 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002926
2927 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002928 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2929 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002930 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002931
drhbfe66312006-10-03 17:40:40 +00002932 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002933 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002934 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002935 */
drh308c2a52010-05-14 11:30:18 +00002936 if( pFile->eFileLock>=eFileLock ){
2937 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2938 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002939 return SQLITE_OK;
2940 }
2941
2942 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002943 ** (1) We never move from unlocked to anything higher than shared lock.
2944 ** (2) SQLite never explicitly requests a pendig lock.
2945 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002946 */
drh308c2a52010-05-14 11:30:18 +00002947 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2948 assert( eFileLock!=PENDING_LOCK );
2949 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002950
drh8af6c222010-05-14 12:43:01 +00002951 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002952 */
drh8af6c222010-05-14 12:43:01 +00002953 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00002954 sqlite3_mutex_enter(pInode->pLockMutex);
drh7ed97b92010-01-20 13:07:21 +00002955
2956 /* If some thread using this PID has a lock via a different unixFile*
2957 ** handle that precludes the requested lock, return BUSY.
2958 */
drh8af6c222010-05-14 12:43:01 +00002959 if( (pFile->eFileLock!=pInode->eFileLock &&
2960 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002961 ){
2962 rc = SQLITE_BUSY;
2963 goto afp_end_lock;
2964 }
2965
2966 /* If a SHARED lock is requested, and some thread using this PID already
2967 ** has a SHARED or RESERVED lock, then increment reference counts and
2968 ** return SQLITE_OK.
2969 */
drh308c2a52010-05-14 11:30:18 +00002970 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002971 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002972 assert( eFileLock==SHARED_LOCK );
2973 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002974 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002975 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002976 pInode->nShared++;
2977 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002978 goto afp_end_lock;
2979 }
drhbfe66312006-10-03 17:40:40 +00002980
2981 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002982 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2983 ** be released.
2984 */
drh308c2a52010-05-14 11:30:18 +00002985 if( eFileLock==SHARED_LOCK
2986 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002987 ){
2988 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002989 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002990 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002991 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002992 goto afp_end_lock;
2993 }
2994 }
2995
2996 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002997 ** operating system calls for the specified lock.
2998 */
drh308c2a52010-05-14 11:30:18 +00002999 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00003000 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00003001 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00003002
drh8af6c222010-05-14 12:43:01 +00003003 assert( pInode->nShared==0 );
3004 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00003005
3006 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00003007 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00003008 /* note that the quality of the randomness doesn't matter that much */
3009 lk = random();
drh8af6c222010-05-14 12:43:01 +00003010 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00003011 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003012 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00003013 if( IS_LOCK_ERROR(lrc1) ){
3014 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00003015 }
aswift5b1a2562008-08-22 00:22:35 +00003016 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00003017 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00003018
aswift5b1a2562008-08-22 00:22:35 +00003019 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00003020 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00003021 rc = lrc1;
3022 goto afp_end_lock;
3023 } else if( IS_LOCK_ERROR(lrc2) ){
3024 rc = lrc2;
3025 goto afp_end_lock;
3026 } else if( lrc1 != SQLITE_OK ) {
3027 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00003028 } else {
drh308c2a52010-05-14 11:30:18 +00003029 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00003030 pInode->nLock++;
3031 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00003032 }
drh8af6c222010-05-14 12:43:01 +00003033 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00003034 /* We are trying for an exclusive lock but another thread in this
3035 ** same process is still holding a shared lock. */
3036 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00003037 }else{
3038 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3039 ** assumed that there is a SHARED or greater lock on the file
3040 ** already.
3041 */
3042 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00003043 assert( 0!=pFile->eFileLock );
3044 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003045 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00003046 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00003047 if( !failed ){
3048 context->reserved = 1;
3049 }
drhbfe66312006-10-03 17:40:40 +00003050 }
drh308c2a52010-05-14 11:30:18 +00003051 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003052 /* Acquire an EXCLUSIVE lock */
3053
3054 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00003055 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00003056 */
drh6b9d6dd2008-12-03 19:34:47 +00003057 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00003058 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00003059 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00003060 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00003061 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00003062 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00003063 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003064 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00003065 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3066 ** a critical I/O error
3067 */
drh2e233812017-08-22 15:21:54 +00003068 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00003069 SQLITE_IOERR_LOCK;
3070 goto afp_end_lock;
3071 }
3072 }else{
aswift5b1a2562008-08-22 00:22:35 +00003073 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003074 }
3075 }
aswift5b1a2562008-08-22 00:22:35 +00003076 if( failed ){
3077 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003078 }
3079 }
3080
3081 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00003082 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00003083 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00003084 }else if( eFileLock==EXCLUSIVE_LOCK ){
3085 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00003086 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00003087 }
3088
3089afp_end_lock:
drhda6dc242018-07-23 21:10:37 +00003090 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00003091 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3092 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00003093 return rc;
3094}
3095
3096/*
drh308c2a52010-05-14 11:30:18 +00003097** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00003098** must be either NO_LOCK or SHARED_LOCK.
3099**
3100** If the locking level of the file descriptor is already at or below
3101** the requested locking level, this routine is a no-op.
3102*/
drh308c2a52010-05-14 11:30:18 +00003103static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00003104 int rc = SQLITE_OK;
3105 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00003106 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00003107 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3108 int skipShared = 0;
3109#ifdef SQLITE_TEST
3110 int h = pFile->h;
3111#endif
drhbfe66312006-10-03 17:40:40 +00003112
3113 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003114 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00003115 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00003116 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00003117
drh308c2a52010-05-14 11:30:18 +00003118 assert( eFileLock<=SHARED_LOCK );
3119 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00003120 return SQLITE_OK;
3121 }
drh8af6c222010-05-14 12:43:01 +00003122 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00003123 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00003124 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00003125 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00003126 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00003127 SimulateIOErrorBenign(1);
3128 SimulateIOError( h=(-1) )
3129 SimulateIOErrorBenign(0);
3130
drhd3d8c042012-05-29 17:02:40 +00003131#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003132 /* When reducing a lock such that other processes can start
3133 ** reading the database file again, make sure that the
3134 ** transaction counter was updated if any part of the database
3135 ** file changed. If the transaction counter is not updated,
3136 ** other connections to the same file might not realize that
3137 ** the file has changed and hence might not know to flush their
3138 ** cache. The use of a stale cache can lead to database corruption.
3139 */
3140 assert( pFile->inNormalWrite==0
3141 || pFile->dbUpdate==0
3142 || pFile->transCntrChng==1 );
3143 pFile->inNormalWrite = 0;
3144#endif
aswiftaebf4132008-11-21 00:10:35 +00003145
drh308c2a52010-05-14 11:30:18 +00003146 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003147 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003148 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003149 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003150 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003151 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3152 } else {
3153 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003154 }
3155 }
drh308c2a52010-05-14 11:30:18 +00003156 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003157 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003158 }
drh308c2a52010-05-14 11:30:18 +00003159 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003160 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3161 if( !rc ){
3162 context->reserved = 0;
3163 }
aswiftaebf4132008-11-21 00:10:35 +00003164 }
drh8af6c222010-05-14 12:43:01 +00003165 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3166 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003167 }
aswiftaebf4132008-11-21 00:10:35 +00003168 }
drh308c2a52010-05-14 11:30:18 +00003169 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003170
drh7ed97b92010-01-20 13:07:21 +00003171 /* Decrement the shared lock counter. Release the lock using an
3172 ** OS call only when all threads in this same process have released
3173 ** the lock.
3174 */
drh8af6c222010-05-14 12:43:01 +00003175 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3176 pInode->nShared--;
3177 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003178 SimulateIOErrorBenign(1);
3179 SimulateIOError( h=(-1) )
3180 SimulateIOErrorBenign(0);
3181 if( !skipShared ){
3182 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3183 }
3184 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003185 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003186 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003187 }
3188 }
3189 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003190 pInode->nLock--;
3191 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00003192 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003193 }
drhbfe66312006-10-03 17:40:40 +00003194 }
drh7ed97b92010-01-20 13:07:21 +00003195
drhda6dc242018-07-23 21:10:37 +00003196 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00003197 if( rc==SQLITE_OK ){
3198 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00003199 }
drhbfe66312006-10-03 17:40:40 +00003200 return rc;
3201}
3202
3203/*
drh339eb0b2008-03-07 15:34:11 +00003204** Close a file & cleanup AFP specific locking context
3205*/
danielk1977e339d652008-06-28 11:23:00 +00003206static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003207 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003208 unixFile *pFile = (unixFile*)id;
3209 assert( id!=0 );
3210 afpUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00003211 assert( unixFileMutexNotheld(pFile) );
drha8de1e12015-11-30 00:05:39 +00003212 unixEnterMutex();
drhef52b362018-08-13 22:50:34 +00003213 if( pFile->pInode ){
3214 unixInodeInfo *pInode = pFile->pInode;
3215 sqlite3_mutex_enter(pInode->pLockMutex);
drhcb4e4b02018-09-06 19:36:29 +00003216 if( pInode->nLock ){
drhef52b362018-08-13 22:50:34 +00003217 /* If there are outstanding locks, do not actually close the file just
3218 ** yet because that would clear those locks. Instead, add the file
3219 ** descriptor to pInode->aPending. It will be automatically closed when
3220 ** the last lock is cleared.
3221 */
3222 setPendingFd(pFile);
3223 }
3224 sqlite3_mutex_leave(pInode->pLockMutex);
danielk1977e339d652008-06-28 11:23:00 +00003225 }
drha8de1e12015-11-30 00:05:39 +00003226 releaseInodeInfo(pFile);
3227 sqlite3_free(pFile->lockingContext);
3228 rc = closeUnixFile(id);
3229 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003230 return rc;
drhbfe66312006-10-03 17:40:40 +00003231}
3232
drhd2cb50b2009-01-09 21:41:17 +00003233#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003234/*
3235** The code above is the AFP lock implementation. The code is specific
3236** to MacOSX and does not work on other unix platforms. No alternative
3237** is available. If you don't compile for a mac, then the "unix-afp"
3238** VFS is not available.
3239**
3240********************* End of the AFP lock implementation **********************
3241******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003242
drh7ed97b92010-01-20 13:07:21 +00003243/******************************************************************************
3244*************************** Begin NFS Locking ********************************/
3245
3246#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3247/*
drh308c2a52010-05-14 11:30:18 +00003248 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003249 ** must be either NO_LOCK or SHARED_LOCK.
3250 **
3251 ** If the locking level of the file descriptor is already at or below
3252 ** the requested locking level, this routine is a no-op.
3253 */
drh308c2a52010-05-14 11:30:18 +00003254static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003255 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003256}
3257
3258#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3259/*
3260** The code above is the NFS lock implementation. The code is specific
3261** to MacOSX and does not work on other unix platforms. No alternative
3262** is available.
3263**
3264********************* End of the NFS lock implementation **********************
3265******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003266
3267/******************************************************************************
3268**************** Non-locking sqlite3_file methods *****************************
3269**
3270** The next division contains implementations for all methods of the
3271** sqlite3_file object other than the locking methods. The locking
3272** methods were defined in divisions above (one locking method per
3273** division). Those methods that are common to all locking modes
3274** are gather together into this division.
3275*/
drhbfe66312006-10-03 17:40:40 +00003276
3277/*
drh734c9862008-11-28 15:37:20 +00003278** Seek to the offset passed as the second argument, then read cnt
3279** bytes into pBuf. Return the number of bytes actually read.
3280**
3281** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3282** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3283** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003284** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003285** See tickets #2741 and #2681.
3286**
3287** To avoid stomping the errno value on a failed read the lastErrno value
3288** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003289*/
drh734c9862008-11-28 15:37:20 +00003290static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3291 int got;
drh58024642011-11-07 18:16:00 +00003292 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003293#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3294 i64 newOffset;
3295#endif
drh734c9862008-11-28 15:37:20 +00003296 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003297 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003298 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003299 do{
drh734c9862008-11-28 15:37:20 +00003300#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003301 got = osPread(id->h, pBuf, cnt, offset);
3302 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003303#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003304 got = osPread64(id->h, pBuf, cnt, offset);
3305 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003306#else
drha46cadc2016-03-04 03:02:06 +00003307 newOffset = lseek(id->h, offset, SEEK_SET);
3308 SimulateIOError( newOffset = -1 );
3309 if( newOffset<0 ){
3310 storeLastErrno((unixFile*)id, errno);
3311 return -1;
3312 }
3313 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003314#endif
drh58024642011-11-07 18:16:00 +00003315 if( got==cnt ) break;
3316 if( got<0 ){
3317 if( errno==EINTR ){ got = 1; continue; }
3318 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003319 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003320 break;
3321 }else if( got>0 ){
3322 cnt -= got;
3323 offset += got;
3324 prior += got;
3325 pBuf = (void*)(got + (char*)pBuf);
3326 }
3327 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003328 TIMER_END;
drh58024642011-11-07 18:16:00 +00003329 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3330 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3331 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003332}
3333
3334/*
drh734c9862008-11-28 15:37:20 +00003335** Read data from a file into a buffer. Return SQLITE_OK if all
3336** bytes were read successfully and SQLITE_IOERR if anything goes
3337** wrong.
drh339eb0b2008-03-07 15:34:11 +00003338*/
drh734c9862008-11-28 15:37:20 +00003339static int unixRead(
3340 sqlite3_file *id,
3341 void *pBuf,
3342 int amt,
3343 sqlite3_int64 offset
3344){
dan08da86a2009-08-21 17:18:03 +00003345 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003346 int got;
3347 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003348 assert( offset>=0 );
3349 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003350
drh067b92b2020-06-19 15:24:12 +00003351 /* If this is a database file (not a journal, super-journal or temp
dan08da86a2009-08-21 17:18:03 +00003352 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003353#if 0
drhc68886b2017-08-18 16:09:52 +00003354 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003355 || offset>=PENDING_BYTE+512
3356 || offset+amt<=PENDING_BYTE
3357 );
dan7c246102010-04-12 19:00:29 +00003358#endif
drh08c6d442009-02-09 17:34:07 +00003359
drh9b4c59f2013-04-15 17:03:42 +00003360#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003361 /* Deal with as much of this read request as possible by transfering
3362 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003363 if( offset<pFile->mmapSize ){
3364 if( offset+amt <= pFile->mmapSize ){
3365 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3366 return SQLITE_OK;
3367 }else{
3368 int nCopy = pFile->mmapSize - offset;
3369 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3370 pBuf = &((u8 *)pBuf)[nCopy];
3371 amt -= nCopy;
3372 offset += nCopy;
3373 }
3374 }
drh6e0b6d52013-04-09 16:19:20 +00003375#endif
danf23da962013-03-23 21:00:41 +00003376
dan08da86a2009-08-21 17:18:03 +00003377 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003378 if( got==amt ){
3379 return SQLITE_OK;
3380 }else if( got<0 ){
drh5a07d102020-11-18 12:48:48 +00003381 /* pFile->lastErrno has been set by seekAndRead().
3382 ** Usually we return SQLITE_IOERR_READ here, though for some
3383 ** kinds of errors we return SQLITE_IOERR_CORRUPTFS. The
3384 ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT
3385 ** prior to returning to the application by the sqlite3ApiExit()
3386 ** routine.
3387 */
3388 switch( pFile->lastErrno ){
3389 case ERANGE:
drh5a07d102020-11-18 12:48:48 +00003390 case EIO:
3391#ifdef ENXIO
3392 case ENXIO:
3393#endif
3394#ifdef EDEVERR
3395 case EDEVERR:
3396#endif
3397 return SQLITE_IOERR_CORRUPTFS;
3398 }
drh734c9862008-11-28 15:37:20 +00003399 return SQLITE_IOERR_READ;
3400 }else{
drh4bf66fd2015-02-19 02:43:02 +00003401 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003402 /* Unread parts of the buffer must be zero-filled */
3403 memset(&((char*)pBuf)[got], 0, amt-got);
3404 return SQLITE_IOERR_SHORT_READ;
3405 }
3406}
3407
3408/*
dan47a2b4a2013-04-26 16:09:29 +00003409** Attempt to seek the file-descriptor passed as the first argument to
3410** absolute offset iOff, then attempt to write nBuf bytes of data from
3411** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3412** return the actual number of bytes written (which may be less than
3413** nBuf).
3414*/
3415static int seekAndWriteFd(
3416 int fd, /* File descriptor to write to */
3417 i64 iOff, /* File offset to begin writing at */
3418 const void *pBuf, /* Copy data from this buffer to the file */
3419 int nBuf, /* Size of buffer pBuf in bytes */
3420 int *piErrno /* OUT: Error number if error occurs */
3421){
3422 int rc = 0; /* Value returned by system call */
3423
3424 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003425 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003426 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003427 nBuf &= 0x1ffff;
3428 TIMER_START;
3429
3430#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003431 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003432#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003433 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003434#else
3435 do{
3436 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003437 SimulateIOError( iSeek = -1 );
3438 if( iSeek<0 ){
3439 rc = -1;
3440 break;
dan47a2b4a2013-04-26 16:09:29 +00003441 }
3442 rc = osWrite(fd, pBuf, nBuf);
3443 }while( rc<0 && errno==EINTR );
3444#endif
3445
3446 TIMER_END;
3447 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3448
drhe1818ec2015-12-01 16:21:35 +00003449 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003450 return rc;
3451}
3452
3453
3454/*
drh734c9862008-11-28 15:37:20 +00003455** Seek to the offset in id->offset then read cnt bytes into pBuf.
3456** Return the number of bytes actually read. Update the offset.
3457**
3458** To avoid stomping the errno value on a failed write the lastErrno value
3459** is set before returning.
3460*/
3461static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003462 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003463}
3464
3465
3466/*
3467** Write data from a buffer into a file. Return SQLITE_OK on success
3468** or some other error code on failure.
3469*/
3470static int unixWrite(
3471 sqlite3_file *id,
3472 const void *pBuf,
3473 int amt,
3474 sqlite3_int64 offset
3475){
dan08da86a2009-08-21 17:18:03 +00003476 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003477 int wrote = 0;
3478 assert( id );
3479 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003480
drh067b92b2020-06-19 15:24:12 +00003481 /* If this is a database file (not a journal, super-journal or temp
dan08da86a2009-08-21 17:18:03 +00003482 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003483#if 0
drhc68886b2017-08-18 16:09:52 +00003484 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003485 || offset>=PENDING_BYTE+512
3486 || offset+amt<=PENDING_BYTE
3487 );
dan7c246102010-04-12 19:00:29 +00003488#endif
drh08c6d442009-02-09 17:34:07 +00003489
drhd3d8c042012-05-29 17:02:40 +00003490#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003491 /* If we are doing a normal write to a database file (as opposed to
3492 ** doing a hot-journal rollback or a write to some file other than a
3493 ** normal database file) then record the fact that the database
3494 ** has changed. If the transaction counter is modified, record that
3495 ** fact too.
3496 */
dan08da86a2009-08-21 17:18:03 +00003497 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003498 pFile->dbUpdate = 1; /* The database has been modified */
3499 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003500 int rc;
drh8f941bc2009-01-14 23:03:40 +00003501 char oldCntr[4];
3502 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003503 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003504 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003505 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003506 pFile->transCntrChng = 1; /* The transaction counter has changed */
3507 }
3508 }
3509 }
3510#endif
3511
danfe33e392015-11-17 20:56:06 +00003512#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003513 /* Deal with as much of this write request as possible by transfering
3514 ** data from the memory mapping using memcpy(). */
3515 if( offset<pFile->mmapSize ){
3516 if( offset+amt <= pFile->mmapSize ){
3517 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3518 return SQLITE_OK;
3519 }else{
3520 int nCopy = pFile->mmapSize - offset;
3521 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3522 pBuf = &((u8 *)pBuf)[nCopy];
3523 amt -= nCopy;
3524 offset += nCopy;
3525 }
3526 }
drh6e0b6d52013-04-09 16:19:20 +00003527#endif
drh02bf8b42015-09-01 23:51:53 +00003528
3529 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003530 amt -= wrote;
3531 offset += wrote;
3532 pBuf = &((char*)pBuf)[wrote];
3533 }
3534 SimulateIOError(( wrote=(-1), amt=1 ));
3535 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003536
drh02bf8b42015-09-01 23:51:53 +00003537 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003538 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003539 /* lastErrno set by seekAndWrite */
3540 return SQLITE_IOERR_WRITE;
3541 }else{
drh4bf66fd2015-02-19 02:43:02 +00003542 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003543 return SQLITE_FULL;
3544 }
3545 }
dan6e09d692010-07-27 18:34:15 +00003546
drh734c9862008-11-28 15:37:20 +00003547 return SQLITE_OK;
3548}
3549
3550#ifdef SQLITE_TEST
3551/*
3552** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003553** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003554*/
3555int sqlite3_sync_count = 0;
3556int sqlite3_fullsync_count = 0;
3557#endif
3558
3559/*
drh89240432009-03-25 01:06:01 +00003560** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003561** Others do no. To be safe, we will stick with the (slightly slower)
3562** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003563** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003564*/
drhf7a4a1b2015-01-10 18:02:45 +00003565#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003566# define fdatasync fsync
3567#endif
3568
3569/*
3570** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3571** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3572** only available on Mac OS X. But that could change.
3573*/
3574#ifdef F_FULLFSYNC
3575# define HAVE_FULLFSYNC 1
3576#else
3577# define HAVE_FULLFSYNC 0
3578#endif
3579
3580
3581/*
3582** The fsync() system call does not work as advertised on many
3583** unix systems. The following procedure is an attempt to make
3584** it work better.
3585**
3586** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3587** for testing when we want to run through the test suite quickly.
3588** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3589** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3590** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003591**
3592** SQLite sets the dataOnly flag if the size of the file is unchanged.
3593** The idea behind dataOnly is that it should only write the file content
3594** to disk, not the inode. We only set dataOnly if the file size is
3595** unchanged since the file size is part of the inode. However,
3596** Ted Ts'o tells us that fdatasync() will also write the inode if the
3597** file size has changed. The only real difference between fdatasync()
3598** and fsync(), Ted tells us, is that fdatasync() will not flush the
3599** inode if the mtime or owner or other inode attributes have changed.
3600** We only care about the file size, not the other file attributes, so
3601** as far as SQLite is concerned, an fdatasync() is always adequate.
3602** So, we always use fdatasync() if it is available, regardless of
3603** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003604*/
3605static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003606 int rc;
drh734c9862008-11-28 15:37:20 +00003607
3608 /* The following "ifdef/elif/else/" block has the same structure as
3609 ** the one below. It is replicated here solely to avoid cluttering
3610 ** up the real code with the UNUSED_PARAMETER() macros.
3611 */
3612#ifdef SQLITE_NO_SYNC
3613 UNUSED_PARAMETER(fd);
3614 UNUSED_PARAMETER(fullSync);
3615 UNUSED_PARAMETER(dataOnly);
3616#elif HAVE_FULLFSYNC
3617 UNUSED_PARAMETER(dataOnly);
3618#else
3619 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003620 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003621#endif
3622
3623 /* Record the number of times that we do a normal fsync() and
3624 ** FULLSYNC. This is used during testing to verify that this procedure
3625 ** gets called with the correct arguments.
3626 */
3627#ifdef SQLITE_TEST
3628 if( fullSync ) sqlite3_fullsync_count++;
3629 sqlite3_sync_count++;
3630#endif
3631
3632 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003633 ** no-op. But go ahead and call fstat() to validate the file
3634 ** descriptor as we need a method to provoke a failure during
3635 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003636 */
3637#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003638 {
3639 struct stat buf;
3640 rc = osFstat(fd, &buf);
3641 }
drh734c9862008-11-28 15:37:20 +00003642#elif HAVE_FULLFSYNC
3643 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003644 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003645 }else{
3646 rc = 1;
3647 }
3648 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003649 ** It shouldn't be possible for fullfsync to fail on the local
3650 ** file system (on OSX), so failure indicates that FULLFSYNC
3651 ** isn't supported for this file system. So, attempt an fsync
3652 ** and (for now) ignore the overhead of a superfluous fcntl call.
3653 ** It'd be better to detect fullfsync support once and avoid
3654 ** the fcntl call every time sync is called.
3655 */
drh734c9862008-11-28 15:37:20 +00003656 if( rc ) rc = fsync(fd);
3657
drh7ed97b92010-01-20 13:07:21 +00003658#elif defined(__APPLE__)
3659 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3660 ** so currently we default to the macro that redefines fdatasync to fsync
3661 */
3662 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003663#else
drh0b647ff2009-03-21 14:41:04 +00003664 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003665#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003666 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003667 rc = fsync(fd);
3668 }
drh0b647ff2009-03-21 14:41:04 +00003669#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003670#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3671
3672 if( OS_VXWORKS && rc!= -1 ){
3673 rc = 0;
3674 }
chw97185482008-11-17 08:05:31 +00003675 return rc;
drhbfe66312006-10-03 17:40:40 +00003676}
3677
drh734c9862008-11-28 15:37:20 +00003678/*
drh0059eae2011-08-08 23:48:40 +00003679** Open a file descriptor to the directory containing file zFilename.
3680** If successful, *pFd is set to the opened file descriptor and
3681** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3682** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3683** value.
3684**
drh90315a22011-08-10 01:52:12 +00003685** The directory file descriptor is used for only one thing - to
3686** fsync() a directory to make sure file creation and deletion events
3687** are flushed to disk. Such fsyncs are not needed on newer
3688** journaling filesystems, but are required on older filesystems.
3689**
3690** This routine can be overridden using the xSetSysCall interface.
3691** The ability to override this routine was added in support of the
3692** chromium sandbox. Opening a directory is a security risk (we are
3693** told) so making it overrideable allows the chromium sandbox to
3694** replace this routine with a harmless no-op. To make this routine
3695** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3696** *pFd set to a negative number.
3697**
drh0059eae2011-08-08 23:48:40 +00003698** If SQLITE_OK is returned, the caller is responsible for closing
3699** the file descriptor *pFd using close().
3700*/
3701static int openDirectory(const char *zFilename, int *pFd){
3702 int ii;
3703 int fd = -1;
3704 char zDirname[MAX_PATHNAME+1];
3705
3706 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003707 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3708 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003709 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003710 }else{
3711 if( zDirname[0]!='/' ) zDirname[0] = '.';
3712 zDirname[1] = 0;
3713 }
drh3b9f1542020-04-20 17:35:32 +00003714 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drhdc278512015-12-07 18:18:33 +00003715 if( fd>=0 ){
3716 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003717 }
3718 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003719 if( fd>=0 ) return SQLITE_OK;
3720 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003721}
3722
3723/*
drh734c9862008-11-28 15:37:20 +00003724** Make sure all writes to a particular file are committed to disk.
3725**
3726** If dataOnly==0 then both the file itself and its metadata (file
3727** size, access time, etc) are synced. If dataOnly!=0 then only the
3728** file data is synced.
3729**
3730** Under Unix, also make sure that the directory entry for the file
3731** has been created by fsync-ing the directory that contains the file.
3732** If we do not do this and we encounter a power failure, the directory
3733** entry for the journal might not exist after we reboot. The next
3734** SQLite to access the file will not know that the journal exists (because
3735** the directory entry for the journal was never created) and the transaction
3736** will not roll back - possibly leading to database corruption.
3737*/
3738static int unixSync(sqlite3_file *id, int flags){
3739 int rc;
3740 unixFile *pFile = (unixFile*)id;
3741
3742 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3743 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3744
3745 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3746 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3747 || (flags&0x0F)==SQLITE_SYNC_FULL
3748 );
3749
3750 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3751 ** line is to test that doing so does not cause any problems.
3752 */
3753 SimulateDiskfullError( return SQLITE_FULL );
3754
3755 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003756 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003757 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3758 SimulateIOError( rc=1 );
3759 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003760 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003761 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003762 }
drh0059eae2011-08-08 23:48:40 +00003763
3764 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003765 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003766 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003767 */
3768 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3769 int dirfd;
3770 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003771 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003772 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003773 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003774 full_fsync(dirfd, 0, 0);
3775 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003776 }else{
3777 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003778 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003779 }
drh0059eae2011-08-08 23:48:40 +00003780 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003781 }
3782 return rc;
3783}
3784
3785/*
3786** Truncate an open file to a specified size
3787*/
3788static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003789 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003790 int rc;
dan6e09d692010-07-27 18:34:15 +00003791 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003792 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003793
3794 /* If the user has configured a chunk-size for this file, truncate the
3795 ** file so that it consists of an integer number of chunks (i.e. the
3796 ** actual file size after the operation may be larger than the requested
3797 ** size).
3798 */
drhb8af4b72012-04-05 20:04:39 +00003799 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003800 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3801 }
3802
dan2ee53412014-09-06 16:49:40 +00003803 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003804 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003805 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003806 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003807 }else{
drhd3d8c042012-05-29 17:02:40 +00003808#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003809 /* If we are doing a normal write to a database file (as opposed to
3810 ** doing a hot-journal rollback or a write to some file other than a
3811 ** normal database file) and we truncate the file to zero length,
3812 ** that effectively updates the change counter. This might happen
3813 ** when restoring a database using the backup API from a zero-length
3814 ** source.
3815 */
dan6e09d692010-07-27 18:34:15 +00003816 if( pFile->inNormalWrite && nByte==0 ){
3817 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003818 }
danf23da962013-03-23 21:00:41 +00003819#endif
danc0003312013-03-22 17:46:11 +00003820
mistachkine98844f2013-08-24 00:59:24 +00003821#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003822 /* If the file was just truncated to a size smaller than the currently
3823 ** mapped region, reduce the effective mapping size as well. SQLite will
3824 ** use read() and write() to access data beyond this point from now on.
3825 */
3826 if( nByte<pFile->mmapSize ){
3827 pFile->mmapSize = nByte;
3828 }
mistachkine98844f2013-08-24 00:59:24 +00003829#endif
drh3313b142009-11-06 04:13:18 +00003830
drh734c9862008-11-28 15:37:20 +00003831 return SQLITE_OK;
3832 }
3833}
3834
3835/*
3836** Determine the current size of a file in bytes
3837*/
3838static int unixFileSize(sqlite3_file *id, i64 *pSize){
3839 int rc;
3840 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003841 assert( id );
3842 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003843 SimulateIOError( rc=1 );
3844 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003845 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003846 return SQLITE_IOERR_FSTAT;
3847 }
3848 *pSize = buf.st_size;
3849
drh8af6c222010-05-14 12:43:01 +00003850 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003851 ** writes a single byte into that file in order to work around a bug
3852 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3853 ** layers, we need to report this file size as zero even though it is
3854 ** really 1. Ticket #3260.
3855 */
3856 if( *pSize==1 ) *pSize = 0;
3857
3858
3859 return SQLITE_OK;
3860}
3861
drhd2cb50b2009-01-09 21:41:17 +00003862#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003863/*
3864** Handler for proxy-locking file-control verbs. Defined below in the
3865** proxying locking division.
3866*/
3867static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003868#endif
drh715ff302008-12-03 22:32:44 +00003869
dan502019c2010-07-28 14:26:17 +00003870/*
3871** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003872** file-control operation. Enlarge the database to nBytes in size
3873** (rounded up to the next chunk-size). If the database is already
3874** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003875*/
3876static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003877 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003878 i64 nSize; /* Required file size */
3879 struct stat buf; /* Used to hold return values of fstat() */
3880
drh4bf66fd2015-02-19 02:43:02 +00003881 if( osFstat(pFile->h, &buf) ){
3882 return SQLITE_IOERR_FSTAT;
3883 }
dan502019c2010-07-28 14:26:17 +00003884
3885 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3886 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003887
dan502019c2010-07-28 14:26:17 +00003888#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003889 /* The code below is handling the return value of osFallocate()
3890 ** correctly. posix_fallocate() is defined to "returns zero on success,
3891 ** or an error number on failure". See the manpage for details. */
3892 int err;
drhff812312011-02-23 13:33:46 +00003893 do{
dan661d71a2011-03-30 19:08:03 +00003894 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3895 }while( err==EINTR );
drh789df142018-06-02 14:37:39 +00003896 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003897#else
dan592bf7f2014-12-30 19:58:31 +00003898 /* If the OS does not have posix_fallocate(), fake it. Write a
3899 ** single byte to the last byte in each block that falls entirely
3900 ** within the extended region. Then, if required, a single byte
3901 ** at offset (nSize-1), to set the size of the file correctly.
3902 ** This is a similar technique to that used by glibc on systems
3903 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003904 */
3905 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003906 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003907 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003908
drh053378d2015-12-01 22:09:42 +00003909 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003910 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003911 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003912 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3913 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003914 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003915 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003916 }
dan502019c2010-07-28 14:26:17 +00003917#endif
3918 }
3919 }
3920
mistachkine98844f2013-08-24 00:59:24 +00003921#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003922 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003923 int rc;
3924 if( pFile->szChunk<=0 ){
3925 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003926 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003927 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3928 }
3929 }
3930
3931 rc = unixMapfile(pFile, nByte);
3932 return rc;
3933 }
mistachkine98844f2013-08-24 00:59:24 +00003934#endif
danf23da962013-03-23 21:00:41 +00003935
dan502019c2010-07-28 14:26:17 +00003936 return SQLITE_OK;
3937}
danielk1977ad94b582007-08-20 06:44:22 +00003938
danielk1977e3026632004-06-22 11:29:02 +00003939/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003940** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003941** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3942**
3943** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3944*/
3945static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3946 if( *pArg<0 ){
3947 *pArg = (pFile->ctrlFlags & mask)!=0;
3948 }else if( (*pArg)==0 ){
3949 pFile->ctrlFlags &= ~mask;
3950 }else{
3951 pFile->ctrlFlags |= mask;
3952 }
3953}
3954
drh696b33e2012-12-06 19:01:42 +00003955/* Forward declaration */
3956static int unixGetTempname(int nBuf, char *zBuf);
dana12a40c2021-11-02 11:09:24 +00003957#ifndef SQLITE_OMIT_WAL
3958 static int unixFcntlExternalReader(unixFile*, int*);
3959#endif
drh696b33e2012-12-06 19:01:42 +00003960
drhf12b3f62011-12-21 14:42:29 +00003961/*
drh9e33c2c2007-08-31 18:34:59 +00003962** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003963*/
drhcc6bb3e2007-08-31 16:11:35 +00003964static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003965 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003966 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003967#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003968 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3969 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003970 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003971 }
3972 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3973 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003974 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003975 }
3976 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3977 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003978 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003979 }
drhd76dba72017-07-22 16:00:34 +00003980#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003981
drh9e33c2c2007-08-31 18:34:59 +00003982 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003983 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003984 return SQLITE_OK;
3985 }
drh4bf66fd2015-02-19 02:43:02 +00003986 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003987 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003988 return SQLITE_OK;
3989 }
dan6e09d692010-07-27 18:34:15 +00003990 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003991 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003992 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003993 }
drh9ff27ec2010-05-19 19:26:05 +00003994 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003995 int rc;
3996 SimulateIOErrorBenign(1);
3997 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3998 SimulateIOErrorBenign(0);
3999 return rc;
drhf0b190d2011-07-26 16:03:07 +00004000 }
4001 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00004002 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
4003 return SQLITE_OK;
4004 }
drhcb15f352011-12-23 01:04:17 +00004005 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
4006 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00004007 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00004008 }
drhde60fc22011-12-14 17:53:36 +00004009 case SQLITE_FCNTL_VFSNAME: {
4010 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
4011 return SQLITE_OK;
4012 }
drh696b33e2012-12-06 19:01:42 +00004013 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00004014 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00004015 if( zTFile ){
4016 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
4017 *(char**)pArg = zTFile;
4018 }
4019 return SQLITE_OK;
4020 }
drhb959a012013-12-07 12:29:22 +00004021 case SQLITE_FCNTL_HAS_MOVED: {
4022 *(int*)pArg = fileHasMoved(pFile);
4023 return SQLITE_OK;
4024 }
drhf0119b22018-03-26 17:40:53 +00004025#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4026 case SQLITE_FCNTL_LOCK_TIMEOUT: {
dan97ccc1b2020-03-27 17:23:17 +00004027 int iOld = pFile->iBusyTimeout;
drhf0119b22018-03-26 17:40:53 +00004028 pFile->iBusyTimeout = *(int*)pArg;
dan97ccc1b2020-03-27 17:23:17 +00004029 *(int*)pArg = iOld;
drhf0119b22018-03-26 17:40:53 +00004030 return SQLITE_OK;
4031 }
4032#endif
mistachkine98844f2013-08-24 00:59:24 +00004033#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00004034 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00004035 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00004036 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00004037 if( newLimit>sqlite3GlobalConfig.mxMmap ){
4038 newLimit = sqlite3GlobalConfig.mxMmap;
4039 }
dan43c1e622017-08-07 18:13:28 +00004040
4041 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00004042 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4043 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00004044 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00004045 newLimit = (newLimit & 0x7FFFFFFF);
4046 }
4047
drh9b4c59f2013-04-15 17:03:42 +00004048 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00004049 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00004050 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00004051 if( pFile->mmapSize>0 ){
4052 unixUnmapfile(pFile);
4053 rc = unixMapfile(pFile, -1);
4054 }
danbcb8a862013-04-08 15:30:41 +00004055 }
drh34e258c2013-05-23 01:40:53 +00004056 return rc;
danb2d3de32013-03-14 18:34:37 +00004057 }
mistachkine98844f2013-08-24 00:59:24 +00004058#endif
drhd3d8c042012-05-29 17:02:40 +00004059#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00004060 /* The pager calls this method to signal that it has done
4061 ** a rollback and that the database is therefore unchanged and
4062 ** it hence it is OK for the transaction change counter to be
4063 ** unchanged.
4064 */
4065 case SQLITE_FCNTL_DB_UNCHANGED: {
4066 ((unixFile*)id)->dbUpdate = 0;
4067 return SQLITE_OK;
4068 }
4069#endif
drhd2cb50b2009-01-09 21:41:17 +00004070#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00004071 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4072 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00004073 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00004074 }
drhd2cb50b2009-01-09 21:41:17 +00004075#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
danaecc04d2021-04-02 19:55:48 +00004076
4077 case SQLITE_FCNTL_EXTERNAL_READER: {
dana12a40c2021-11-02 11:09:24 +00004078#ifndef SQLITE_OMIT_WAL
danaecc04d2021-04-02 19:55:48 +00004079 return unixFcntlExternalReader((unixFile*)id, (int*)pArg);
dana12a40c2021-11-02 11:09:24 +00004080#else
4081 *(int*)pArg = 0;
4082 return SQLITE_OK;
4083#endif
danaecc04d2021-04-02 19:55:48 +00004084 }
drh9e33c2c2007-08-31 18:34:59 +00004085 }
drh0b52b7d2011-01-26 19:46:22 +00004086 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00004087}
4088
4089/*
danefe16972017-07-20 19:49:14 +00004090** If pFd->sectorSize is non-zero when this function is called, it is a
4091** no-op. Otherwise, the values of pFd->sectorSize and
4092** pFd->deviceCharacteristics are set according to the file-system
4093** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00004094**
danefe16972017-07-20 19:49:14 +00004095** There are two versions of this function. One for QNX and one for all
4096** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00004097*/
danefe16972017-07-20 19:49:14 +00004098#ifndef __QNXNTO__
4099static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00004100 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00004101 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00004102#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00004103 int res;
dan9d709542017-07-21 21:06:24 +00004104 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00004105
danefe16972017-07-20 19:49:14 +00004106 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00004107 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4108 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00004109 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00004110 }
drhd76dba72017-07-22 16:00:34 +00004111#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00004112
4113 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4114 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4115 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4116 }
4117
4118 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4119 }
4120}
4121#else
drh537dddf2012-10-26 13:46:24 +00004122#include <sys/dcmd_blk.h>
4123#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00004124static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00004125 if( pFile->sectorSize == 0 ){
4126 struct statvfs fsInfo;
4127
4128 /* Set defaults for non-supported filesystems */
4129 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4130 pFile->deviceCharacteristics = 0;
4131 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00004132 return;
drh537dddf2012-10-26 13:46:24 +00004133 }
4134
4135 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4136 pFile->sectorSize = fsInfo.f_bsize;
4137 pFile->deviceCharacteristics =
4138 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
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( strstr(fsInfo.f_basetype, "etfs") ){
4145 pFile->sectorSize = fsInfo.f_bsize;
4146 pFile->deviceCharacteristics =
4147 /* etfs cluster size writes are atomic */
4148 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4149 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4150 ** the write succeeds */
4151 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4152 ** so it is ordered */
4153 0;
4154 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4155 pFile->sectorSize = fsInfo.f_bsize;
4156 pFile->deviceCharacteristics =
4157 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4158 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4159 ** the write succeeds */
4160 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4161 ** so it is ordered */
4162 0;
4163 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4164 pFile->sectorSize = fsInfo.f_bsize;
4165 pFile->deviceCharacteristics =
4166 /* full bitset of atomics from max sector size and smaller */
4167 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4168 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4169 ** so it is ordered */
4170 0;
4171 }else if( strstr(fsInfo.f_basetype, "dos") ){
4172 pFile->sectorSize = fsInfo.f_bsize;
4173 pFile->deviceCharacteristics =
4174 /* full bitset of atomics from max sector size and smaller */
4175 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4176 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4177 ** so it is ordered */
4178 0;
4179 }else{
4180 pFile->deviceCharacteristics =
4181 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4182 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4183 ** the write succeeds */
4184 0;
4185 }
4186 }
4187 /* Last chance verification. If the sector size isn't a multiple of 512
4188 ** then it isn't valid.*/
4189 if( pFile->sectorSize % 512 != 0 ){
4190 pFile->deviceCharacteristics = 0;
4191 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4192 }
drh537dddf2012-10-26 13:46:24 +00004193}
danefe16972017-07-20 19:49:14 +00004194#endif
4195
4196/*
4197** Return the sector size in bytes of the underlying block device for
4198** the specified file. This is almost always 512 bytes, but may be
4199** larger for some devices.
4200**
4201** SQLite code assumes this function cannot fail. It also assumes that
4202** if two files are created in the same file-system directory (i.e.
4203** a database and its journal file) that the sector size will be the
4204** same for both.
4205*/
4206static int unixSectorSize(sqlite3_file *id){
4207 unixFile *pFd = (unixFile*)id;
4208 setDeviceCharacteristics(pFd);
4209 return pFd->sectorSize;
4210}
danielk1977a3d4c882007-03-23 10:08:38 +00004211
danielk197790949c22007-08-17 16:50:38 +00004212/*
drhf12b3f62011-12-21 14:42:29 +00004213** Return the device characteristics for the file.
4214**
drhcb15f352011-12-23 01:04:17 +00004215** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004216** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004217** file system does not always provide powersafe overwrites. (In other
4218** words, after a power-loss event, parts of the file that were never
4219** written might end up being altered.) However, non-PSOW behavior is very,
4220** very rare. And asserting PSOW makes a large reduction in the amount
4221** of required I/O for journaling, since a lot of padding is eliminated.
4222** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4223** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004224*/
drhf12b3f62011-12-21 14:42:29 +00004225static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004226 unixFile *pFd = (unixFile*)id;
4227 setDeviceCharacteristics(pFd);
4228 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004229}
4230
dan702eec12014-06-23 10:04:58 +00004231#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004232
dan702eec12014-06-23 10:04:58 +00004233/*
4234** Return the system page size.
4235**
4236** This function should not be called directly by other code in this file.
4237** Instead, it should be called via macro osGetpagesize().
4238*/
4239static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004240#if OS_VXWORKS
4241 return 1024;
4242#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004243 return getpagesize();
4244#else
4245 return (int)sysconf(_SC_PAGESIZE);
4246#endif
4247}
4248
4249#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4250
4251#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004252
4253/*
drhd91c68f2010-05-14 14:52:25 +00004254** Object used to represent an shared memory buffer.
4255**
4256** When multiple threads all reference the same wal-index, each thread
4257** has its own unixShm object, but they all point to a single instance
4258** of this unixShmNode object. In other words, each wal-index is opened
4259** only once per process.
4260**
4261** Each unixShmNode object is connected to a single unixInodeInfo object.
4262** We could coalesce this object into unixInodeInfo, but that would mean
4263** every open file that does not use shared memory (in other words, most
4264** open files) would have to carry around this extra information. So
4265** the unixInodeInfo object contains a pointer to this unixShmNode object
4266** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004267**
4268** unixMutexHeld() must be true when creating or destroying
4269** this object or while reading or writing the following fields:
4270**
4271** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004272**
4273** The following fields are read-only after the object is created:
4274**
drh8820c8d2018-10-02 19:58:08 +00004275** hShm
drhd9e5c4f2010-05-12 18:01:39 +00004276** zFilename
4277**
drh8820c8d2018-10-02 19:58:08 +00004278** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004279** unixMutexHeld() is true when reading or writing any other field
4280** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004281*/
drhd91c68f2010-05-14 14:52:25 +00004282struct unixShmNode {
4283 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drh24efa542018-10-02 19:36:40 +00004284 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004285 char *zFilename; /* Name of the mmapped file */
drh8820c8d2018-10-02 19:58:08 +00004286 int hShm; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004287 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004288 u16 nRegion; /* Size of array apRegion */
4289 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004290 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004291 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004292 int nRef; /* Number of unixShm objects pointing to this */
4293 unixShm *pFirst; /* All unixShm objects pointing to this */
dan8337da62020-08-28 19:27:15 +00004294 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
drhd9e5c4f2010-05-12 18:01:39 +00004295#ifdef SQLITE_DEBUG
4296 u8 exclMask; /* Mask of exclusive locks held */
4297 u8 sharedMask; /* Mask of shared locks held */
4298 u8 nextShmId; /* Next available unixShm.id value */
4299#endif
4300};
4301
4302/*
drhd9e5c4f2010-05-12 18:01:39 +00004303** Structure used internally by this VFS to record the state of an
4304** open shared memory connection.
4305**
drhd91c68f2010-05-14 14:52:25 +00004306** The following fields are initialized when this object is created and
4307** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004308**
drh24efa542018-10-02 19:36:40 +00004309** unixShm.pShmNode
drhd91c68f2010-05-14 14:52:25 +00004310** unixShm.id
4311**
drh24efa542018-10-02 19:36:40 +00004312** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4313** be held while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004314*/
4315struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004316 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4317 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drh24efa542018-10-02 19:36:40 +00004318 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
drhfd532312011-08-31 18:35:34 +00004319 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004320 u16 sharedMask; /* Mask of shared locks held */
4321 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004322};
4323
4324/*
drhd9e5c4f2010-05-12 18:01:39 +00004325** Constants used for locking
4326*/
drhbd9676c2010-06-23 17:58:38 +00004327#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004328#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004329
drhd9e5c4f2010-05-12 18:01:39 +00004330/*
danaecc04d2021-04-02 19:55:48 +00004331** Use F_GETLK to check whether or not there are any readers with open
4332** wal-mode transactions in other processes on database file pFile. If
4333** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are
4334** such transactions, or 0 otherwise. If an error occurs, return an
4335** SQLite error code. The final value of *piOut is undefined in this
4336** case.
4337*/
4338static int unixFcntlExternalReader(unixFile *pFile, int *piOut){
4339 int rc = SQLITE_OK;
4340 *piOut = 0;
4341 if( pFile->pShm){
4342 unixShmNode *pShmNode = pFile->pShm->pShmNode;
4343 struct flock f;
4344
4345 memset(&f, 0, sizeof(f));
4346 f.l_type = F_WRLCK;
4347 f.l_whence = SEEK_SET;
4348 f.l_start = UNIX_SHM_BASE + 3;
4349 f.l_len = SQLITE_SHM_NLOCK - 3;
4350
4351 sqlite3_mutex_enter(pShmNode->pShmMutex);
4352 if( osFcntl(pShmNode->hShm, F_GETLK, &f)<0 ){
4353 rc = SQLITE_IOERR_LOCK;
4354 }else{
4355 *piOut = (f.l_type!=F_UNLCK);
4356 }
4357 sqlite3_mutex_leave(pShmNode->pShmMutex);
4358 }
4359
4360 return rc;
4361}
4362
4363
4364/*
drh73b64e42010-05-30 19:55:15 +00004365** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004366**
4367** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4368** otherwise.
4369*/
4370static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004371 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004372 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004373 int ofst, /* First byte of the locking range */
4374 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004375){
drhbbf76ee2015-03-10 20:22:35 +00004376 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4377 struct flock f; /* The posix advisory locking structure */
4378 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004379
drhd91c68f2010-05-14 14:52:25 +00004380 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004381 pShmNode = pFile->pInode->pShmNode;
drh24efa542018-10-02 19:36:40 +00004382 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
drh9b7e8e12018-10-02 20:16:41 +00004383 assert( pShmNode->nRef>0 || unixMutexHeld() );
drhd9e5c4f2010-05-12 18:01:39 +00004384
dan9181ae92017-10-26 17:05:22 +00004385 /* Shared locks never span more than one byte */
4386 assert( n==1 || lockType!=F_RDLCK );
4387
4388 /* Locks are within range */
4389 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4390
drh8820c8d2018-10-02 19:58:08 +00004391 if( pShmNode->hShm>=0 ){
dan7bb8b8a2020-05-06 20:27:18 +00004392 int res;
drh3cb93392011-03-12 18:10:44 +00004393 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004394 f.l_type = lockType;
4395 f.l_whence = SEEK_SET;
4396 f.l_start = ofst;
4397 f.l_len = n;
dan7bb8b8a2020-05-06 20:27:18 +00004398 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
4399 if( res==-1 ){
dan7a623e12020-05-06 20:45:11 +00004400#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
dan7bb8b8a2020-05-06 20:27:18 +00004401 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
dan7a623e12020-05-06 20:45:11 +00004402#else
4403 rc = SQLITE_BUSY;
4404#endif
dan7bb8b8a2020-05-06 20:27:18 +00004405 }
drh3cb93392011-03-12 18:10:44 +00004406 }
drhd9e5c4f2010-05-12 18:01:39 +00004407
4408 /* Update the global lock state and do debug tracing */
4409#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004410 { u16 mask;
4411 OSTRACE(("SHM-LOCK "));
4412 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4413 if( rc==SQLITE_OK ){
4414 if( lockType==F_UNLCK ){
4415 OSTRACE(("unlock %d ok", ofst));
4416 pShmNode->exclMask &= ~mask;
4417 pShmNode->sharedMask &= ~mask;
4418 }else if( lockType==F_RDLCK ){
4419 OSTRACE(("read-lock %d ok", ofst));
4420 pShmNode->exclMask &= ~mask;
4421 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004422 }else{
dan9181ae92017-10-26 17:05:22 +00004423 assert( lockType==F_WRLCK );
4424 OSTRACE(("write-lock %d ok", ofst));
4425 pShmNode->exclMask |= mask;
4426 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004427 }
dan9181ae92017-10-26 17:05:22 +00004428 }else{
4429 if( lockType==F_UNLCK ){
4430 OSTRACE(("unlock %d failed", ofst));
4431 }else if( lockType==F_RDLCK ){
4432 OSTRACE(("read-lock failed"));
4433 }else{
4434 assert( lockType==F_WRLCK );
4435 OSTRACE(("write-lock %d failed", ofst));
4436 }
4437 }
4438 OSTRACE((" - afterwards %03x,%03x\n",
4439 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004440 }
drhd9e5c4f2010-05-12 18:01:39 +00004441#endif
4442
4443 return rc;
4444}
4445
dan781e34c2014-03-20 08:59:47 +00004446/*
dan781e34c2014-03-20 08:59:47 +00004447** Return the minimum number of 32KB shm regions that should be mapped at
4448** a time, assuming that each mapping must be an integer multiple of the
4449** current system page-size.
4450**
4451** Usually, this is 1. The exception seems to be systems that are configured
4452** to use 64KB pages - in this case each mapping must cover at least two
4453** shm regions.
4454*/
4455static int unixShmRegionPerMap(void){
4456 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004457 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004458 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4459 if( pgsz<shmsz ) return 1;
4460 return pgsz/shmsz;
4461}
drhd9e5c4f2010-05-12 18:01:39 +00004462
4463/*
drhd91c68f2010-05-14 14:52:25 +00004464** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004465**
4466** This is not a VFS shared-memory method; it is a utility function called
4467** by VFS shared-memory methods.
4468*/
drhd91c68f2010-05-14 14:52:25 +00004469static void unixShmPurge(unixFile *pFd){
4470 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004471 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004472 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004473 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004474 int i;
drhd91c68f2010-05-14 14:52:25 +00004475 assert( p->pInode==pFd->pInode );
drh24efa542018-10-02 19:36:40 +00004476 sqlite3_mutex_free(p->pShmMutex);
dan781e34c2014-03-20 08:59:47 +00004477 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh8820c8d2018-10-02 19:58:08 +00004478 if( p->hShm>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004479 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004480 }else{
4481 sqlite3_free(p->apRegion[i]);
4482 }
dan13a3cb82010-06-11 19:04:21 +00004483 }
dan18801912010-06-14 14:07:50 +00004484 sqlite3_free(p->apRegion);
drh8820c8d2018-10-02 19:58:08 +00004485 if( p->hShm>=0 ){
4486 robust_close(pFd, p->hShm, __LINE__);
4487 p->hShm = -1;
drh0e9365c2011-03-02 02:08:13 +00004488 }
drhd91c68f2010-05-14 14:52:25 +00004489 p->pInode->pShmNode = 0;
4490 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004491 }
4492}
4493
4494/*
dan92c02da2017-11-01 20:59:28 +00004495** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4496** take it now. Return SQLITE_OK if successful, or an SQLite error
4497** code otherwise.
4498**
4499** If the DMS cannot be locked because this is a readonly_shm=1
4500** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004501** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004502*/
4503static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4504 struct flock lock;
4505 int rc = SQLITE_OK;
4506
4507 /* Use F_GETLK to determine the locks other processes are holding
4508 ** on the DMS byte. If it indicates that another process is holding
4509 ** a SHARED lock, then this process may also take a SHARED lock
4510 ** and proceed with opening the *-shm file.
4511 **
4512 ** Or, if no other process is holding any lock, then this process
4513 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4514 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4515 ** downgrade to a SHARED lock on the DMS byte.
4516 **
4517 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4518 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4519 ** version of this code attempted the SHARED lock at this point. But
4520 ** this introduced a subtle race condition: if the process holding
4521 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4522 ** process might open and use the *-shm file without truncating it.
4523 ** And if the *-shm file has been corrupted by a power failure or
4524 ** system crash, the database itself may also become corrupt. */
4525 lock.l_whence = SEEK_SET;
4526 lock.l_start = UNIX_SHM_DMS;
4527 lock.l_len = 1;
4528 lock.l_type = F_WRLCK;
drh8820c8d2018-10-02 19:58:08 +00004529 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
dan92c02da2017-11-01 20:59:28 +00004530 rc = SQLITE_IOERR_LOCK;
4531 }else if( lock.l_type==F_UNLCK ){
4532 if( pShmNode->isReadonly ){
4533 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004534 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004535 }else{
4536 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
drhf7f2a822018-10-11 13:51:48 +00004537 /* The first connection to attach must truncate the -shm file. We
4538 ** truncate to 3 bytes (an arbitrary small number, less than the
4539 ** -shm header size) rather than 0 as a system debugging aid, to
4540 ** help detect if a -shm file truncation is legitimate or is the work
4541 ** or a rogue process. */
4542 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
dan92c02da2017-11-01 20:59:28 +00004543 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4544 }
4545 }
4546 }else if( lock.l_type==F_WRLCK ){
4547 rc = SQLITE_BUSY;
4548 }
4549
4550 if( rc==SQLITE_OK ){
4551 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4552 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4553 }
4554 return rc;
4555}
4556
4557/*
danda9fe0c2010-07-13 18:44:03 +00004558** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004559** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004560**
drh7234c6d2010-06-19 15:10:09 +00004561** The file used to implement shared-memory is in the same directory
4562** as the open database file and has the same name as the open database
4563** file with the "-shm" suffix added. For example, if the database file
4564** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004565** for shared memory will be called "/home/user1/config.db-shm".
4566**
4567** Another approach to is to use files in /dev/shm or /dev/tmp or an
4568** some other tmpfs mount. But if a file in a different directory
4569** from the database file is used, then differing access permissions
4570** or a chroot() might cause two different processes on the same
4571** database to end up using different files for shared memory -
4572** meaning that their memory would not really be shared - resulting
4573** in database corruption. Nevertheless, this tmpfs file usage
4574** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4575** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4576** option results in an incompatible build of SQLite; builds of SQLite
4577** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4578** same database file at the same time, database corruption will likely
4579** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4580** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004581**
4582** When opening a new shared-memory file, if no other instances of that
4583** file are currently open, in this process or in other processes, then
4584** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004585**
4586** If the original database file (pDbFd) is using the "unix-excl" VFS
4587** that means that an exclusive lock is held on the database file and
4588** that no other processes are able to read or write the database. In
4589** that case, we do not really need shared memory. No shared memory
4590** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004591*/
danda9fe0c2010-07-13 18:44:03 +00004592static int unixOpenSharedMemory(unixFile *pDbFd){
4593 struct unixShm *p = 0; /* The connection to be opened */
4594 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004595 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004596 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004597 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004598 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004599
danda9fe0c2010-07-13 18:44:03 +00004600 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004601 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004602 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004603 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004604 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004605
danda9fe0c2010-07-13 18:44:03 +00004606 /* Check to see if a unixShmNode object already exists. Reuse an existing
4607 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004608 */
drh095908e2018-08-13 20:46:18 +00004609 assert( unixFileMutexNotheld(pDbFd) );
drhd9e5c4f2010-05-12 18:01:39 +00004610 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004611 pInode = pDbFd->pInode;
4612 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004613 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004614 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004615#ifndef SQLITE_SHM_DIRECTORY
4616 const char *zBasePath = pDbFd->zPath;
4617#endif
danddb0ac42010-07-14 14:48:58 +00004618
4619 /* Call fstat() to figure out the permissions on the database file. If
4620 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004621 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004622 */
drhf3b1ed02015-12-02 13:11:03 +00004623 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004624 rc = SQLITE_IOERR_FSTAT;
4625 goto shm_open_err;
4626 }
4627
drha4ced192010-07-15 18:32:40 +00004628#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004629 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004630#else
drh4bf66fd2015-02-19 02:43:02 +00004631 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004632#endif
drhf3cdcdc2015-04-29 16:50:28 +00004633 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004634 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004635 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004636 goto shm_open_err;
4637 }
drh9cb5a0d2012-01-05 21:19:54 +00004638 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004639 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004640#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004641 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004642 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4643 (u32)sStat.st_ino, (u32)sStat.st_dev);
4644#else
danf12ba662017-11-07 15:43:52 +00004645 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4646 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004647#endif
drh8820c8d2018-10-02 19:58:08 +00004648 pShmNode->hShm = -1;
drhd91c68f2010-05-14 14:52:25 +00004649 pDbFd->pInode->pShmNode = pShmNode;
4650 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004651 if( sqlite3GlobalConfig.bCoreMutex ){
drh24efa542018-10-02 19:36:40 +00004652 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4653 if( pShmNode->pShmMutex==0 ){
drh97a7e5e2016-04-26 18:58:54 +00004654 rc = SQLITE_NOMEM_BKPT;
4655 goto shm_open_err;
4656 }
drhd91c68f2010-05-14 14:52:25 +00004657 }
drhd9e5c4f2010-05-12 18:01:39 +00004658
drh3cb93392011-03-12 18:10:44 +00004659 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004660 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drhc398c652019-11-22 00:42:01 +00004661 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
4662 (sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004663 }
drh8820c8d2018-10-02 19:58:08 +00004664 if( pShmNode->hShm<0 ){
drhc398c652019-11-22 00:42:01 +00004665 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
4666 (sStat.st_mode&0777));
drh8820c8d2018-10-02 19:58:08 +00004667 if( pShmNode->hShm<0 ){
danf12ba662017-11-07 15:43:52 +00004668 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4669 goto shm_open_err;
4670 }
4671 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004672 }
drhac7c3ac2012-02-11 19:23:48 +00004673
4674 /* If this process is running as root, make sure that the SHM file
4675 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004676 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004677 */
drh8820c8d2018-10-02 19:58:08 +00004678 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004679
dan92c02da2017-11-01 20:59:28 +00004680 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004681 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004682 }
drhd9e5c4f2010-05-12 18:01:39 +00004683 }
4684
drhd91c68f2010-05-14 14:52:25 +00004685 /* Make the new connection a child of the unixShmNode */
4686 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004687#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004688 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004689#endif
drhd91c68f2010-05-14 14:52:25 +00004690 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004691 pDbFd->pShm = p;
4692 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004693
4694 /* The reference count on pShmNode has already been incremented under
4695 ** the cover of the unixEnterMutex() mutex and the pointer from the
4696 ** new (struct unixShm) object to the pShmNode has been set. All that is
4697 ** left to do is to link the new object into the linked list starting
drh24efa542018-10-02 19:36:40 +00004698 ** at pShmNode->pFirst. This must be done while holding the
4699 ** pShmNode->pShmMutex.
dan0668f592010-07-20 18:59:00 +00004700 */
drh24efa542018-10-02 19:36:40 +00004701 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan0668f592010-07-20 18:59:00 +00004702 p->pNext = pShmNode->pFirst;
4703 pShmNode->pFirst = p;
drh24efa542018-10-02 19:36:40 +00004704 sqlite3_mutex_leave(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004705 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004706
4707 /* Jump here on any error */
4708shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004709 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004710 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004711 unixLeaveMutex();
4712 return rc;
4713}
4714
4715/*
danda9fe0c2010-07-13 18:44:03 +00004716** This function is called to obtain a pointer to region iRegion of the
4717** shared-memory associated with the database file fd. Shared-memory regions
4718** are numbered starting from zero. Each shared-memory region is szRegion
4719** bytes in size.
4720**
4721** If an error occurs, an error code is returned and *pp is set to NULL.
4722**
4723** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4724** region has not been allocated (by any client, including one running in a
4725** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4726** bExtend is non-zero and the requested shared-memory region has not yet
4727** been allocated, it is allocated by this function.
4728**
4729** If the shared-memory region has already been allocated or is allocated by
4730** this call as described above, then it is mapped into this processes
4731** address space (if it is not already), *pp is set to point to the mapped
4732** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004733*/
danda9fe0c2010-07-13 18:44:03 +00004734static int unixShmMap(
4735 sqlite3_file *fd, /* Handle open on database file */
4736 int iRegion, /* Region to retrieve */
4737 int szRegion, /* Size of regions */
4738 int bExtend, /* True to extend file if necessary */
4739 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004740){
danda9fe0c2010-07-13 18:44:03 +00004741 unixFile *pDbFd = (unixFile*)fd;
4742 unixShm *p;
4743 unixShmNode *pShmNode;
4744 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004745 int nShmPerMap = unixShmRegionPerMap();
4746 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004747
danda9fe0c2010-07-13 18:44:03 +00004748 /* If the shared-memory file has not yet been opened, open it now. */
4749 if( pDbFd->pShm==0 ){
4750 rc = unixOpenSharedMemory(pDbFd);
4751 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004752 }
drhd9e5c4f2010-05-12 18:01:39 +00004753
danda9fe0c2010-07-13 18:44:03 +00004754 p = pDbFd->pShm;
4755 pShmNode = p->pShmNode;
drh24efa542018-10-02 19:36:40 +00004756 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004757 if( pShmNode->isUnlocked ){
4758 rc = unixLockSharedMemory(pDbFd, pShmNode);
4759 if( rc!=SQLITE_OK ) goto shmpage_out;
4760 pShmNode->isUnlocked = 0;
4761 }
danda9fe0c2010-07-13 18:44:03 +00004762 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004763 assert( pShmNode->pInode==pDbFd->pInode );
drh8820c8d2018-10-02 19:58:08 +00004764 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4765 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004766
dan781e34c2014-03-20 08:59:47 +00004767 /* Minimum number of regions required to be mapped. */
4768 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4769
4770 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004771 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004772 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004773 struct stat sStat; /* Used by fstat() */
4774
4775 pShmNode->szRegion = szRegion;
4776
drh8820c8d2018-10-02 19:58:08 +00004777 if( pShmNode->hShm>=0 ){
drh3cb93392011-03-12 18:10:44 +00004778 /* The requested region is not mapped into this processes address space.
4779 ** Check to see if it has been allocated (i.e. if the wal-index file is
4780 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004781 */
drh8820c8d2018-10-02 19:58:08 +00004782 if( osFstat(pShmNode->hShm, &sStat) ){
drh3cb93392011-03-12 18:10:44 +00004783 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004784 goto shmpage_out;
4785 }
drh3cb93392011-03-12 18:10:44 +00004786
4787 if( sStat.st_size<nByte ){
4788 /* The requested memory region does not exist. If bExtend is set to
4789 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004790 */
dan47a2b4a2013-04-26 16:09:29 +00004791 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004792 goto shmpage_out;
4793 }
dan47a2b4a2013-04-26 16:09:29 +00004794
4795 /* Alternatively, if bExtend is true, extend the file. Do this by
4796 ** writing a single byte to the end of each (OS) page being
4797 ** allocated or extended. Technically, we need only write to the
4798 ** last page in order to extend the file. But writing to all new
4799 ** pages forces the OS to allocate them immediately, which reduces
4800 ** the chances of SIGBUS while accessing the mapped region later on.
4801 */
4802 else{
4803 static const int pgsz = 4096;
4804 int iPg;
4805
4806 /* Write to the last byte of each newly allocated or extended page */
4807 assert( (nByte % pgsz)==0 );
4808 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004809 int x = 0;
drh8820c8d2018-10-02 19:58:08 +00004810 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004811 const char *zFile = pShmNode->zFilename;
4812 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4813 goto shmpage_out;
4814 }
4815 }
drh3cb93392011-03-12 18:10:44 +00004816 }
4817 }
danda9fe0c2010-07-13 18:44:03 +00004818 }
4819
4820 /* Map the requested memory region into this processes address space. */
4821 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004822 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004823 );
4824 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004825 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004826 goto shmpage_out;
4827 }
4828 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004829 while( pShmNode->nRegion<nReqRegion ){
4830 int nMap = szRegion*nShmPerMap;
4831 int i;
drh3cb93392011-03-12 18:10:44 +00004832 void *pMem;
drh8820c8d2018-10-02 19:58:08 +00004833 if( pShmNode->hShm>=0 ){
dan781e34c2014-03-20 08:59:47 +00004834 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004835 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh8820c8d2018-10-02 19:58:08 +00004836 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004837 );
4838 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004839 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004840 goto shmpage_out;
4841 }
4842 }else{
drhb6c4d592018-10-11 02:39:11 +00004843 pMem = sqlite3_malloc64(nMap);
drh3cb93392011-03-12 18:10:44 +00004844 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004845 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004846 goto shmpage_out;
4847 }
drhb6c4d592018-10-11 02:39:11 +00004848 memset(pMem, 0, nMap);
danda9fe0c2010-07-13 18:44:03 +00004849 }
dan781e34c2014-03-20 08:59:47 +00004850
4851 for(i=0; i<nShmPerMap; i++){
4852 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4853 }
4854 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004855 }
4856 }
4857
4858shmpage_out:
4859 if( pShmNode->nRegion>iRegion ){
4860 *pp = pShmNode->apRegion[iRegion];
4861 }else{
4862 *pp = 0;
4863 }
drh66dfec8b2011-06-01 20:01:49 +00004864 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
drh24efa542018-10-02 19:36:40 +00004865 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004866 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004867}
4868
4869/*
dan8337da62020-08-28 19:27:15 +00004870** Check that the pShmNode->aLock[] array comports with the locking bitmasks
4871** held by each client. Return true if it does, or false otherwise. This
4872** is to be used in an assert(). e.g.
4873**
4874** assert( assertLockingArrayOk(pShmNode) );
4875*/
4876#ifdef SQLITE_DEBUG
4877static int assertLockingArrayOk(unixShmNode *pShmNode){
4878 unixShm *pX;
4879 int aLock[SQLITE_SHM_NLOCK];
4880 assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
4881
4882 memset(aLock, 0, sizeof(aLock));
4883 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4884 int i;
4885 for(i=0; i<SQLITE_SHM_NLOCK; i++){
4886 if( pX->exclMask & (1<<i) ){
4887 assert( aLock[i]==0 );
4888 aLock[i] = -1;
4889 }else if( pX->sharedMask & (1<<i) ){
4890 assert( aLock[i]>=0 );
4891 aLock[i]++;
4892 }
4893 }
4894 }
4895
4896 assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
4897 return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
4898}
4899#endif
4900
4901/*
drhd9e5c4f2010-05-12 18:01:39 +00004902** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004903**
4904** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4905** different here than in posix. In xShmLock(), one can go from unlocked
4906** to shared and back or from unlocked to exclusive and back. But one may
4907** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004908*/
4909static int unixShmLock(
4910 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004911 int ofst, /* First lock to acquire or release */
4912 int n, /* Number of locks to acquire or release */
4913 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004914){
drh73b64e42010-05-30 19:55:15 +00004915 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
drh56d88aa2022-03-22 19:41:55 +00004916 unixShm *p; /* The shared memory being locked */
4917 unixShmNode *pShmNode; /* The underlying file iNode */
drh73b64e42010-05-30 19:55:15 +00004918 int rc = SQLITE_OK; /* Result code */
4919 u16 mask; /* Mask of locks to take or release */
drh56d88aa2022-03-22 19:41:55 +00004920 int *aLock;
4921
4922 p = pDbFd->pShm;
4923 if( p==0 ) return SQLITE_IOERR_SHMLOCK;
4924 pShmNode = p->pShmNode;
4925 if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK;
4926 aLock = pShmNode->aLock;
drhd9e5c4f2010-05-12 18:01:39 +00004927
drhd91c68f2010-05-14 14:52:25 +00004928 assert( pShmNode==pDbFd->pInode->pShmNode );
4929 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004930 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004931 assert( n>=1 );
4932 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4933 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4934 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4935 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4936 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh8820c8d2018-10-02 19:58:08 +00004937 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4938 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004939
dan58021b22020-05-05 20:30:07 +00004940 /* Check that, if this to be a blocking lock, no locks that occur later
4941 ** in the following list than the lock being obtained are already held:
dan97ccc1b2020-03-27 17:23:17 +00004942 **
4943 ** 1. Checkpointer lock (ofst==1).
dan58021b22020-05-05 20:30:07 +00004944 ** 2. Write lock (ofst==0).
dan97ccc1b2020-03-27 17:23:17 +00004945 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
dan97ccc1b2020-03-27 17:23:17 +00004946 **
4947 ** In other words, if this is a blocking lock, none of the locks that
4948 ** occur later in the above list than the lock being obtained may be
dand31fcd42020-05-29 11:07:20 +00004949 ** held.
4950 **
4951 ** It is not permitted to block on the RECOVER lock.
4952 */
dan97ccc1b2020-03-27 17:23:17 +00004953#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
dan58021b22020-05-05 20:30:07 +00004954 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
4955 (ofst!=2) /* not RECOVER */
dan58021b22020-05-05 20:30:07 +00004956 && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
4957 && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
4958 && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
4959 ));
dan97ccc1b2020-03-27 17:23:17 +00004960#endif
4961
drhc99597c2010-05-31 01:41:15 +00004962 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004963 assert( n>1 || mask==(1<<ofst) );
drh24efa542018-10-02 19:36:40 +00004964 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan8337da62020-08-28 19:27:15 +00004965 assert( assertLockingArrayOk(pShmNode) );
drh73b64e42010-05-30 19:55:15 +00004966 if( flags & SQLITE_SHM_UNLOCK ){
dan6acdee62020-08-28 20:01:06 +00004967 if( (p->exclMask|p->sharedMask) & mask ){
4968 int ii;
4969 int bUnlock = 1;
drh73b64e42010-05-30 19:55:15 +00004970
dan6acdee62020-08-28 20:01:06 +00004971 for(ii=ofst; ii<ofst+n; ii++){
4972 if( aLock[ii]>((p->sharedMask & (1<<ii)) ? 1 : 0) ){
4973 bUnlock = 0;
4974 }
dan8337da62020-08-28 19:27:15 +00004975 }
drh73b64e42010-05-30 19:55:15 +00004976
dan6acdee62020-08-28 20:01:06 +00004977 if( bUnlock ){
4978 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
4979 if( rc==SQLITE_OK ){
4980 memset(&aLock[ofst], 0, sizeof(int)*n);
4981 }
drh78043e82020-11-06 16:48:55 +00004982 }else if( ALWAYS(p->sharedMask & (1<<ofst)) ){
dan6acdee62020-08-28 20:01:06 +00004983 assert( n==1 && aLock[ofst]>1 );
4984 aLock[ofst]--;
4985 }
4986
4987 /* Undo the local locks */
dan8337da62020-08-28 19:27:15 +00004988 if( rc==SQLITE_OK ){
dan6acdee62020-08-28 20:01:06 +00004989 p->exclMask &= ~mask;
4990 p->sharedMask &= ~mask;
4991 }
drhd9e5c4f2010-05-12 18:01:39 +00004992 }
drh73b64e42010-05-30 19:55:15 +00004993 }else if( flags & SQLITE_SHM_SHARED ){
dan8337da62020-08-28 19:27:15 +00004994 assert( n==1 );
4995 assert( (p->exclMask & (1<<ofst))==0 );
4996 if( (p->sharedMask & mask)==0 ){
4997 if( aLock[ofst]<0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004998 rc = SQLITE_BUSY;
dan8337da62020-08-28 19:27:15 +00004999 }else if( aLock[ofst]==0 ){
drhbbf76ee2015-03-10 20:22:35 +00005000 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00005001 }
drh73b64e42010-05-30 19:55:15 +00005002
dan8337da62020-08-28 19:27:15 +00005003 /* Get the local shared locks */
5004 if( rc==SQLITE_OK ){
5005 p->sharedMask |= mask;
5006 aLock[ofst]++;
5007 }
drh73b64e42010-05-30 19:55:15 +00005008 }
5009 }else{
5010 /* Make sure no sibling connections hold locks that will block this
dan8337da62020-08-28 19:27:15 +00005011 ** lock. If any do, return SQLITE_BUSY right away. */
5012 int ii;
5013 for(ii=ofst; ii<ofst+n; ii++){
5014 assert( (p->sharedMask & mask)==0 );
drh78043e82020-11-06 16:48:55 +00005015 if( ALWAYS((p->exclMask & (1<<ii))==0) && aLock[ii] ){
drh73b64e42010-05-30 19:55:15 +00005016 rc = SQLITE_BUSY;
5017 break;
5018 }
5019 }
dan8337da62020-08-28 19:27:15 +00005020
5021 /* Get the exclusive locks at the system level. Then if successful
5022 ** also update the in-memory values. */
drh73b64e42010-05-30 19:55:15 +00005023 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00005024 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00005025 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00005026 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00005027 p->exclMask |= mask;
dan8337da62020-08-28 19:27:15 +00005028 for(ii=ofst; ii<ofst+n; ii++){
5029 aLock[ii] = -1;
5030 }
drhd9e5c4f2010-05-12 18:01:39 +00005031 }
drhd9e5c4f2010-05-12 18:01:39 +00005032 }
5033 }
dan8337da62020-08-28 19:27:15 +00005034 assert( assertLockingArrayOk(pShmNode) );
drh24efa542018-10-02 19:36:40 +00005035 sqlite3_mutex_leave(pShmNode->pShmMutex);
drh20e1f082010-05-31 16:10:12 +00005036 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00005037 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00005038 return rc;
5039}
5040
drh286a2882010-05-20 23:51:06 +00005041/*
5042** Implement a memory barrier or memory fence on shared memory.
5043**
5044** All loads and stores begun before the barrier must complete before
5045** any load or store begun after the barrier.
5046*/
5047static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00005048 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00005049){
drhff828942010-06-26 21:34:06 +00005050 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00005051 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
dana86acc22018-09-12 20:32:19 +00005052 assert( fd->pMethods->xLock==nolockLock
5053 || unixFileMutexNotheld((unixFile*)fd)
5054 );
drh22c733d2015-09-24 12:40:43 +00005055 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00005056 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00005057}
5058
dan18801912010-06-14 14:07:50 +00005059/*
danda9fe0c2010-07-13 18:44:03 +00005060** Close a connection to shared-memory. Delete the underlying
5061** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00005062**
5063** If there is no shared memory associated with the connection then this
5064** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00005065*/
danda9fe0c2010-07-13 18:44:03 +00005066static int unixShmUnmap(
5067 sqlite3_file *fd, /* The underlying database file */
5068 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00005069){
danda9fe0c2010-07-13 18:44:03 +00005070 unixShm *p; /* The connection to be closed */
5071 unixShmNode *pShmNode; /* The underlying shared-memory file */
5072 unixShm **pp; /* For looping over sibling connections */
5073 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00005074
danda9fe0c2010-07-13 18:44:03 +00005075 pDbFd = (unixFile*)fd;
5076 p = pDbFd->pShm;
5077 if( p==0 ) return SQLITE_OK;
5078 pShmNode = p->pShmNode;
5079
5080 assert( pShmNode==pDbFd->pInode->pShmNode );
5081 assert( pShmNode->pInode==pDbFd->pInode );
5082
5083 /* Remove connection p from the set of connections associated
5084 ** with pShmNode */
drh24efa542018-10-02 19:36:40 +00005085 sqlite3_mutex_enter(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00005086 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
5087 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00005088
danda9fe0c2010-07-13 18:44:03 +00005089 /* Free the connection p */
5090 sqlite3_free(p);
5091 pDbFd->pShm = 0;
drh24efa542018-10-02 19:36:40 +00005092 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00005093
5094 /* If pShmNode->nRef has reached 0, then close the underlying
5095 ** shared-memory file, too */
drh095908e2018-08-13 20:46:18 +00005096 assert( unixFileMutexNotheld(pDbFd) );
danda9fe0c2010-07-13 18:44:03 +00005097 unixEnterMutex();
5098 assert( pShmNode->nRef>0 );
5099 pShmNode->nRef--;
5100 if( pShmNode->nRef==0 ){
drh8820c8d2018-10-02 19:58:08 +00005101 if( deleteFlag && pShmNode->hShm>=0 ){
drh4bf66fd2015-02-19 02:43:02 +00005102 osUnlink(pShmNode->zFilename);
5103 }
danda9fe0c2010-07-13 18:44:03 +00005104 unixShmPurge(pDbFd);
5105 }
5106 unixLeaveMutex();
5107
5108 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00005109}
drh286a2882010-05-20 23:51:06 +00005110
danda9fe0c2010-07-13 18:44:03 +00005111
drhd9e5c4f2010-05-12 18:01:39 +00005112#else
drh6b017cc2010-06-14 18:01:46 +00005113# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00005114# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00005115# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00005116# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00005117#endif /* #ifndef SQLITE_OMIT_WAL */
5118
mistachkine98844f2013-08-24 00:59:24 +00005119#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00005120/*
danaef49d72013-03-25 16:28:54 +00005121** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00005122*/
danf23da962013-03-23 21:00:41 +00005123static void unixUnmapfile(unixFile *pFd){
5124 assert( pFd->nFetchOut==0 );
5125 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00005126 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00005127 pFd->pMapRegion = 0;
5128 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00005129 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00005130 }
5131}
dan5d8a1372013-03-19 19:28:06 +00005132
danaef49d72013-03-25 16:28:54 +00005133/*
dane6ecd662013-04-01 17:56:59 +00005134** Attempt to set the size of the memory mapping maintained by file
5135** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5136**
5137** If successful, this function sets the following variables:
5138**
5139** unixFile.pMapRegion
5140** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00005141** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00005142**
5143** If unsuccessful, an error message is logged via sqlite3_log() and
5144** the three variables above are zeroed. In this case SQLite should
5145** continue accessing the database using the xRead() and xWrite()
5146** methods.
5147*/
5148static void unixRemapfile(
5149 unixFile *pFd, /* File descriptor object */
5150 i64 nNew /* Required mapping size */
5151){
dan4ff7bc42013-04-02 12:04:09 +00005152 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00005153 int h = pFd->h; /* File descriptor open on db file */
5154 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00005155 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00005156 u8 *pNew = 0; /* Location of new mapping */
5157 int flags = PROT_READ; /* Flags to pass to mmap() */
5158
5159 assert( pFd->nFetchOut==0 );
5160 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00005161 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00005162 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00005163 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00005164 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00005165
danfe33e392015-11-17 20:56:06 +00005166#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00005167 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00005168#endif
dane6ecd662013-04-01 17:56:59 +00005169
5170 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00005171#if HAVE_MREMAP
5172 i64 nReuse = pFd->mmapSize;
5173#else
danbc760632014-03-20 09:42:09 +00005174 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00005175 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00005176#endif
dane6ecd662013-04-01 17:56:59 +00005177 u8 *pReq = &pOrig[nReuse];
5178
5179 /* Unmap any pages of the existing mapping that cannot be reused. */
5180 if( nReuse!=nOrig ){
5181 osMunmap(pReq, nOrig-nReuse);
5182 }
5183
5184#if HAVE_MREMAP
5185 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00005186 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00005187#else
5188 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5189 if( pNew!=MAP_FAILED ){
5190 if( pNew!=pReq ){
5191 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00005192 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00005193 }else{
5194 pNew = pOrig;
5195 }
5196 }
5197#endif
5198
dan48ccef82013-04-02 20:55:01 +00005199 /* The attempt to extend the existing mapping failed. Free it. */
5200 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00005201 osMunmap(pOrig, nReuse);
5202 }
5203 }
5204
5205 /* If pNew is still NULL, try to create an entirely new mapping. */
5206 if( pNew==0 ){
5207 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00005208 }
5209
dan4ff7bc42013-04-02 12:04:09 +00005210 if( pNew==MAP_FAILED ){
5211 pNew = 0;
5212 nNew = 0;
5213 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5214
5215 /* If the mmap() above failed, assume that all subsequent mmap() calls
5216 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5217 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00005218 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00005219 }
dane6ecd662013-04-01 17:56:59 +00005220 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00005221 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00005222}
5223
5224/*
danaef49d72013-03-25 16:28:54 +00005225** Memory map or remap the file opened by file-descriptor pFd (if the file
5226** is already mapped, the existing mapping is replaced by the new). Or, if
5227** there already exists a mapping for this file, and there are still
5228** outstanding xFetch() references to it, this function is a no-op.
5229**
5230** If parameter nByte is non-negative, then it is the requested size of
5231** the mapping to create. Otherwise, if nByte is less than zero, then the
5232** requested size is the size of the file on disk. The actual size of the
5233** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00005234** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00005235**
5236** SQLITE_OK is returned if no error occurs (even if the mapping is not
5237** recreated as a result of outstanding references) or an SQLite error
5238** code otherwise.
5239*/
drhf3b1ed02015-12-02 13:11:03 +00005240static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00005241 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00005242 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005243 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5244
5245 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00005246 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00005247 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00005248 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00005249 }
drh3044b512014-06-16 16:41:52 +00005250 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00005251 }
drh9b4c59f2013-04-15 17:03:42 +00005252 if( nMap>pFd->mmapSizeMax ){
5253 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00005254 }
5255
drh333e6ca2015-12-02 15:44:39 +00005256 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005257 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00005258 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00005259 }
5260
danf23da962013-03-23 21:00:41 +00005261 return SQLITE_OK;
5262}
mistachkine98844f2013-08-24 00:59:24 +00005263#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00005264
danaef49d72013-03-25 16:28:54 +00005265/*
5266** If possible, return a pointer to a mapping of file fd starting at offset
5267** iOff. The mapping must be valid for at least nAmt bytes.
5268**
5269** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5270** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5271** Finally, if an error does occur, return an SQLite error code. The final
5272** value of *pp is undefined in this case.
5273**
5274** If this function does return a pointer, the caller must eventually
5275** release the reference by calling unixUnfetch().
5276*/
danf23da962013-03-23 21:00:41 +00005277static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00005278#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00005279 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00005280#endif
danf23da962013-03-23 21:00:41 +00005281 *pp = 0;
5282
drh9b4c59f2013-04-15 17:03:42 +00005283#if SQLITE_MAX_MMAP_SIZE>0
5284 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00005285 if( pFd->pMapRegion==0 ){
5286 int rc = unixMapfile(pFd, -1);
5287 if( rc!=SQLITE_OK ) return rc;
5288 }
5289 if( pFd->mmapSize >= iOff+nAmt ){
5290 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5291 pFd->nFetchOut++;
5292 }
5293 }
drh6e0b6d52013-04-09 16:19:20 +00005294#endif
danf23da962013-03-23 21:00:41 +00005295 return SQLITE_OK;
5296}
5297
danaef49d72013-03-25 16:28:54 +00005298/*
dandf737fe2013-03-25 17:00:24 +00005299** If the third argument is non-NULL, then this function releases a
5300** reference obtained by an earlier call to unixFetch(). The second
5301** argument passed to this function must be the same as the corresponding
5302** argument that was passed to the unixFetch() invocation.
5303**
5304** Or, if the third argument is NULL, then this function is being called
5305** to inform the VFS layer that, according to POSIX, any existing mapping
5306** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005307*/
dandf737fe2013-03-25 17:00:24 +00005308static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005309#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005310 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005311 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005312
danaef49d72013-03-25 16:28:54 +00005313 /* If p==0 (unmap the entire file) then there must be no outstanding
5314 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5315 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005316 assert( (p==0)==(pFd->nFetchOut==0) );
5317
dandf737fe2013-03-25 17:00:24 +00005318 /* If p!=0, it must match the iOff value. */
5319 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5320
danf23da962013-03-23 21:00:41 +00005321 if( p ){
5322 pFd->nFetchOut--;
5323 }else{
5324 unixUnmapfile(pFd);
5325 }
5326
5327 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005328#else
5329 UNUSED_PARAMETER(fd);
5330 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005331 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005332#endif
danf23da962013-03-23 21:00:41 +00005333 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005334}
5335
5336/*
drh734c9862008-11-28 15:37:20 +00005337** Here ends the implementation of all sqlite3_file methods.
5338**
5339********************** End sqlite3_file Methods *******************************
5340******************************************************************************/
5341
5342/*
drh6b9d6dd2008-12-03 19:34:47 +00005343** This division contains definitions of sqlite3_io_methods objects that
5344** implement various file locking strategies. It also contains definitions
5345** of "finder" functions. A finder-function is used to locate the appropriate
5346** sqlite3_io_methods object for a particular database file. The pAppData
5347** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5348** the correct finder-function for that VFS.
5349**
5350** Most finder functions return a pointer to a fixed sqlite3_io_methods
5351** object. The only interesting finder-function is autolockIoFinder, which
5352** looks at the filesystem type and tries to guess the best locking
5353** strategy from that.
5354**
peter.d.reid60ec9142014-09-06 16:39:46 +00005355** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005356**
5357** (1) The real finder-function named "FImpt()".
5358**
dane946c392009-08-22 11:39:46 +00005359** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005360**
5361**
5362** A pointer to the F pointer is used as the pAppData value for VFS
5363** objects. We have to do this instead of letting pAppData point
5364** directly at the finder-function since C90 rules prevent a void*
5365** from be cast into a function pointer.
5366**
drh6b9d6dd2008-12-03 19:34:47 +00005367**
drh7708e972008-11-29 00:56:52 +00005368** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005369**
drh7708e972008-11-29 00:56:52 +00005370** * A constant sqlite3_io_methods object call METHOD that has locking
5371** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5372**
5373** * An I/O method finder function called FINDER that returns a pointer
5374** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005375*/
drhe6d41732015-02-21 00:49:00 +00005376#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005377static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005378 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005379 CLOSE, /* xClose */ \
5380 unixRead, /* xRead */ \
5381 unixWrite, /* xWrite */ \
5382 unixTruncate, /* xTruncate */ \
5383 unixSync, /* xSync */ \
5384 unixFileSize, /* xFileSize */ \
5385 LOCK, /* xLock */ \
5386 UNLOCK, /* xUnlock */ \
5387 CKLOCK, /* xCheckReservedLock */ \
5388 unixFileControl, /* xFileControl */ \
5389 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005390 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005391 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005392 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005393 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005394 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005395 unixFetch, /* xFetch */ \
5396 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005397}; \
drh0c2694b2009-09-03 16:23:44 +00005398static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5399 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005400 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005401} \
drh0c2694b2009-09-03 16:23:44 +00005402static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005403 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005404
5405/*
5406** Here are all of the sqlite3_io_methods objects for each of the
5407** locking strategies. Functions that return pointers to these methods
5408** are also created.
5409*/
5410IOMETHODS(
5411 posixIoFinder, /* Finder function name */
5412 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005413 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005414 unixClose, /* xClose method */
5415 unixLock, /* xLock method */
5416 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005417 unixCheckReservedLock, /* xCheckReservedLock method */
5418 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005419)
drh7708e972008-11-29 00:56:52 +00005420IOMETHODS(
5421 nolockIoFinder, /* Finder function name */
5422 nolockIoMethods, /* sqlite3_io_methods object name */
drh3e2c8422018-08-13 11:32:07 +00005423 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005424 nolockClose, /* xClose method */
5425 nolockLock, /* xLock method */
5426 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005427 nolockCheckReservedLock, /* xCheckReservedLock method */
5428 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005429)
drh7708e972008-11-29 00:56:52 +00005430IOMETHODS(
5431 dotlockIoFinder, /* Finder function name */
5432 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005433 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005434 dotlockClose, /* xClose method */
5435 dotlockLock, /* xLock method */
5436 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005437 dotlockCheckReservedLock, /* xCheckReservedLock method */
5438 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005439)
drh7708e972008-11-29 00:56:52 +00005440
drhe89b2912015-03-03 20:42:01 +00005441#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005442IOMETHODS(
5443 flockIoFinder, /* Finder function name */
5444 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005445 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005446 flockClose, /* xClose method */
5447 flockLock, /* xLock method */
5448 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005449 flockCheckReservedLock, /* xCheckReservedLock method */
5450 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005451)
drh7708e972008-11-29 00:56:52 +00005452#endif
5453
drh6c7d5c52008-11-21 20:32:33 +00005454#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005455IOMETHODS(
5456 semIoFinder, /* Finder function name */
5457 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005458 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005459 semXClose, /* xClose method */
5460 semXLock, /* xLock method */
5461 semXUnlock, /* xUnlock method */
5462 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005463 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005464)
aswiftaebf4132008-11-21 00:10:35 +00005465#endif
drh7708e972008-11-29 00:56:52 +00005466
drhd2cb50b2009-01-09 21:41:17 +00005467#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005468IOMETHODS(
5469 afpIoFinder, /* Finder function name */
5470 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005471 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005472 afpClose, /* xClose method */
5473 afpLock, /* xLock method */
5474 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005475 afpCheckReservedLock, /* xCheckReservedLock method */
5476 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005477)
drh715ff302008-12-03 22:32:44 +00005478#endif
5479
5480/*
5481** The proxy locking method is a "super-method" in the sense that it
5482** opens secondary file descriptors for the conch and lock files and
5483** it uses proxy, dot-file, AFP, and flock() locking methods on those
5484** secondary files. For this reason, the division that implements
5485** proxy locking is located much further down in the file. But we need
5486** to go ahead and define the sqlite3_io_methods and finder function
5487** for proxy locking here. So we forward declare the I/O methods.
5488*/
drhd2cb50b2009-01-09 21:41:17 +00005489#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005490static int proxyClose(sqlite3_file*);
5491static int proxyLock(sqlite3_file*, int);
5492static int proxyUnlock(sqlite3_file*, int);
5493static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005494IOMETHODS(
5495 proxyIoFinder, /* Finder function name */
5496 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005497 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005498 proxyClose, /* xClose method */
5499 proxyLock, /* xLock method */
5500 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005501 proxyCheckReservedLock, /* xCheckReservedLock method */
5502 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005503)
aswiftaebf4132008-11-21 00:10:35 +00005504#endif
drh7708e972008-11-29 00:56:52 +00005505
drh7ed97b92010-01-20 13:07:21 +00005506/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5507#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5508IOMETHODS(
5509 nfsIoFinder, /* Finder function name */
5510 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005511 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005512 unixClose, /* xClose method */
5513 unixLock, /* xLock method */
5514 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005515 unixCheckReservedLock, /* xCheckReservedLock method */
5516 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005517)
5518#endif
drh7708e972008-11-29 00:56:52 +00005519
drhd2cb50b2009-01-09 21:41:17 +00005520#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005521/*
drh6b9d6dd2008-12-03 19:34:47 +00005522** This "finder" function attempts to determine the best locking strategy
5523** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005524** object that implements that strategy.
5525**
5526** This is for MacOSX only.
5527*/
drh1875f7a2008-12-08 18:19:17 +00005528static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005529 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005530 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005531){
5532 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005533 const char *zFilesystem; /* Filesystem type name */
5534 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005535 } aMap[] = {
5536 { "hfs", &posixIoMethods },
5537 { "ufs", &posixIoMethods },
5538 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005539 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005540 { "webdav", &nolockIoMethods },
5541 { 0, 0 }
5542 };
5543 int i;
5544 struct statfs fsInfo;
5545 struct flock lockInfo;
5546
5547 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005548 /* If filePath==NULL that means we are dealing with a transient file
5549 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005550 return &nolockIoMethods;
5551 }
5552 if( statfs(filePath, &fsInfo) != -1 ){
5553 if( fsInfo.f_flags & MNT_RDONLY ){
5554 return &nolockIoMethods;
5555 }
5556 for(i=0; aMap[i].zFilesystem; i++){
5557 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5558 return aMap[i].pMethods;
5559 }
5560 }
5561 }
5562
5563 /* Default case. Handles, amongst others, "nfs".
5564 ** Test byte-range lock using fcntl(). If the call succeeds,
5565 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005566 */
drh7708e972008-11-29 00:56:52 +00005567 lockInfo.l_len = 1;
5568 lockInfo.l_start = 0;
5569 lockInfo.l_whence = SEEK_SET;
5570 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005571 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005572 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5573 return &nfsIoMethods;
5574 } else {
5575 return &posixIoMethods;
5576 }
drh7708e972008-11-29 00:56:52 +00005577 }else{
5578 return &dotlockIoMethods;
5579 }
5580}
drh0c2694b2009-09-03 16:23:44 +00005581static const sqlite3_io_methods
5582 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005583
drhd2cb50b2009-01-09 21:41:17 +00005584#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005585
drhe89b2912015-03-03 20:42:01 +00005586#if OS_VXWORKS
5587/*
5588** This "finder" function for VxWorks checks to see if posix advisory
5589** locking works. If it does, then that is what is used. If it does not
5590** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005591*/
drhe89b2912015-03-03 20:42:01 +00005592static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005593 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005594 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005595){
5596 struct flock lockInfo;
5597
5598 if( !filePath ){
5599 /* If filePath==NULL that means we are dealing with a transient file
5600 ** that does not need to be locked. */
5601 return &nolockIoMethods;
5602 }
5603
5604 /* Test if fcntl() is supported and use POSIX style locks.
5605 ** Otherwise fall back to the named semaphore method.
5606 */
5607 lockInfo.l_len = 1;
5608 lockInfo.l_start = 0;
5609 lockInfo.l_whence = SEEK_SET;
5610 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005611 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005612 return &posixIoMethods;
5613 }else{
5614 return &semIoMethods;
5615 }
5616}
drh0c2694b2009-09-03 16:23:44 +00005617static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005618 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005619
drhe89b2912015-03-03 20:42:01 +00005620#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005621
drh7708e972008-11-29 00:56:52 +00005622/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005623** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005624*/
drh0c2694b2009-09-03 16:23:44 +00005625typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005626
aswiftaebf4132008-11-21 00:10:35 +00005627
drh734c9862008-11-28 15:37:20 +00005628/****************************************************************************
5629**************************** sqlite3_vfs methods ****************************
5630**
5631** This division contains the implementation of methods on the
5632** sqlite3_vfs object.
5633*/
5634
danielk1977a3d4c882007-03-23 10:08:38 +00005635/*
danielk1977e339d652008-06-28 11:23:00 +00005636** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005637*/
5638static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005639 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005640 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005641 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005642 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005643 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005644){
drh7708e972008-11-29 00:56:52 +00005645 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005646 unixFile *pNew = (unixFile *)pId;
5647 int rc = SQLITE_OK;
5648
drh8af6c222010-05-14 12:43:01 +00005649 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005650
drhb07028f2011-10-14 21:49:18 +00005651 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005652 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005653
drh308c2a52010-05-14 11:30:18 +00005654 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005655 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005656 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005657 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005658 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005659#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005660 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005661#endif
drhc02a43a2012-01-10 23:18:38 +00005662 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5663 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005664 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005665 }
drh503a6862013-03-01 01:07:17 +00005666 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005667 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005668 }
drh339eb0b2008-03-07 15:34:11 +00005669
drh6c7d5c52008-11-21 20:32:33 +00005670#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005671 pNew->pId = vxworksFindFileId(zFilename);
5672 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005673 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005674 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005675 }
5676#endif
5677
drhc02a43a2012-01-10 23:18:38 +00005678 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005679 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005680 }else{
drh0c2694b2009-09-03 16:23:44 +00005681 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005682#if SQLITE_ENABLE_LOCKING_STYLE
5683 /* Cache zFilename in the locking context (AFP and dotlock override) for
5684 ** proxyLock activation is possible (remote proxy is based on db name)
5685 ** zFilename remains valid until file is closed, to support */
5686 pNew->lockingContext = (void*)zFilename;
5687#endif
drhda0e7682008-07-30 15:27:54 +00005688 }
danielk1977e339d652008-06-28 11:23:00 +00005689
drh7ed97b92010-01-20 13:07:21 +00005690 if( pLockingStyle == &posixIoMethods
5691#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5692 || pLockingStyle == &nfsIoMethods
5693#endif
5694 ){
drh7708e972008-11-29 00:56:52 +00005695 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005696 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005697 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005698 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005699 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005700 ** in two scenarios:
5701 **
5702 ** (a) A call to fstat() failed.
5703 ** (b) A malloc failed.
5704 **
5705 ** Scenario (b) may only occur if the process is holding no other
5706 ** file descriptors open on the same file. If there were other file
5707 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005708 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005709 ** handle h - as it is guaranteed that no posix locks will be released
5710 ** by doing so.
5711 **
5712 ** If scenario (a) caused the error then things are not so safe. The
5713 ** implicit assumption here is that if fstat() fails, things are in
5714 ** such bad shape that dropping a lock or two doesn't matter much.
5715 */
drh0e9365c2011-03-02 02:08:13 +00005716 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005717 h = -1;
5718 }
drh7708e972008-11-29 00:56:52 +00005719 unixLeaveMutex();
5720 }
danielk1977e339d652008-06-28 11:23:00 +00005721
drhd2cb50b2009-01-09 21:41:17 +00005722#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005723 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005724 /* AFP locking uses the file path so it needs to be included in
5725 ** the afpLockingContext.
5726 */
5727 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005728 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005729 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005730 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005731 }else{
5732 /* NB: zFilename exists and remains valid until the file is closed
5733 ** according to requirement F11141. So we do not need to make a
5734 ** copy of the filename. */
5735 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005736 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005737 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005738 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005739 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005740 if( rc!=SQLITE_OK ){
5741 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005742 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005743 h = -1;
5744 }
drh7708e972008-11-29 00:56:52 +00005745 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005746 }
drh7708e972008-11-29 00:56:52 +00005747 }
5748#endif
danielk1977e339d652008-06-28 11:23:00 +00005749
drh7708e972008-11-29 00:56:52 +00005750 else if( pLockingStyle == &dotlockIoMethods ){
5751 /* Dotfile locking uses the file path so it needs to be included in
5752 ** the dotlockLockingContext
5753 */
5754 char *zLockFile;
5755 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005756 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005757 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005758 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005759 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005760 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005761 }else{
5762 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005763 }
drh7708e972008-11-29 00:56:52 +00005764 pNew->lockingContext = zLockFile;
5765 }
danielk1977e339d652008-06-28 11:23:00 +00005766
drh6c7d5c52008-11-21 20:32:33 +00005767#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005768 else if( pLockingStyle == &semIoMethods ){
5769 /* Named semaphore locking uses the file path so it needs to be
5770 ** included in the semLockingContext
5771 */
5772 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005773 rc = findInodeInfo(pNew, &pNew->pInode);
5774 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5775 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005776 int n;
drh2238dcc2009-08-27 17:56:20 +00005777 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005778 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005779 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005780 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005781 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5782 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005783 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005784 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005785 }
chw97185482008-11-17 08:05:31 +00005786 }
drh7708e972008-11-29 00:56:52 +00005787 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005788 }
drh7708e972008-11-29 00:56:52 +00005789#endif
aswift5b1a2562008-08-22 00:22:35 +00005790
drh4bf66fd2015-02-19 02:43:02 +00005791 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005792#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005793 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005794 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005795 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005796 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005797 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005798 }
chw97185482008-11-17 08:05:31 +00005799#endif
danielk1977e339d652008-06-28 11:23:00 +00005800 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005801 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005802 }else{
drh0c52f5a2020-07-24 09:17:42 +00005803 pId->pMethods = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005804 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005805 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005806 }
danielk1977e339d652008-06-28 11:23:00 +00005807 return rc;
drh054889e2005-11-30 03:20:31 +00005808}
drh9c06c952005-11-26 00:25:00 +00005809
danielk1977ad94b582007-08-20 06:44:22 +00005810/*
dand9137e32021-11-19 14:02:43 +00005811** Directories to consider for temp files.
5812*/
5813static const char *azTempDirs[] = {
5814 0,
5815 0,
5816 "/var/tmp",
5817 "/usr/tmp",
5818 "/tmp",
5819 "."
5820};
5821
5822/*
5823** Initialize first two members of azTempDirs[] array.
5824*/
5825static void unixTempFileInit(void){
5826 azTempDirs[0] = getenv("SQLITE_TMPDIR");
5827 azTempDirs[1] = getenv("TMPDIR");
5828}
5829
5830/*
drh8b3cf822010-06-01 21:02:51 +00005831** Return the name of a directory in which to put temporary files.
5832** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005833*/
drh7234c6d2010-06-19 15:10:09 +00005834static const char *unixTempFileDir(void){
drh2aab11f2016-04-29 20:30:56 +00005835 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005836 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005837 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005838
drh2aab11f2016-04-29 20:30:56 +00005839 while(1){
5840 if( zDir!=0
5841 && osStat(zDir, &buf)==0
5842 && S_ISDIR(buf.st_mode)
5843 && osAccess(zDir, 03)==0
5844 ){
5845 return zDir;
5846 }
dand9137e32021-11-19 14:02:43 +00005847 if( i>=sizeof(azTempDirs)/sizeof(azTempDirs[0]) ) break;
5848 zDir = azTempDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005849 }
drh7694e062016-04-21 23:37:24 +00005850 return 0;
drh8b3cf822010-06-01 21:02:51 +00005851}
5852
5853/*
5854** Create a temporary file name in zBuf. zBuf must be allocated
5855** by the calling process and must be big enough to hold at least
5856** pVfs->mxPathname bytes.
5857*/
5858static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005859 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005860 int iLimit = 0;
drh18a3a482022-09-02 00:36:16 +00005861 int rc = SQLITE_OK;
danielk197717b90b52008-06-06 11:11:25 +00005862
5863 /* It's odd to simulate an io-error here, but really this is just
5864 ** using the io-error infrastructure to test that SQLite handles this
5865 ** function failing.
5866 */
drh7694e062016-04-21 23:37:24 +00005867 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005868 SimulateIOError( return SQLITE_IOERR );
5869
drh18a3a482022-09-02 00:36:16 +00005870 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
drh7234c6d2010-06-19 15:10:09 +00005871 zDir = unixTempFileDir();
drh18a3a482022-09-02 00:36:16 +00005872 if( zDir==0 ){
5873 rc = SQLITE_IOERR_GETTEMPPATH;
5874 }else{
5875 do{
5876 u64 r;
5877 sqlite3_randomness(sizeof(r), &r);
5878 assert( nBuf>2 );
5879 zBuf[nBuf-2] = 0;
5880 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5881 zDir, r, 0);
5882 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ){
5883 rc = SQLITE_ERROR;
5884 break;
5885 }
5886 }while( osAccess(zBuf,0)==0 );
5887 }
5888 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
5889 return rc;
danielk197717b90b52008-06-06 11:11:25 +00005890}
5891
drhd2cb50b2009-01-09 21:41:17 +00005892#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005893/*
5894** Routine to transform a unixFile into a proxy-locking unixFile.
5895** Implementation in the proxy-lock division, but used by unixOpen()
5896** if SQLITE_PREFER_PROXY_LOCKING is defined.
5897*/
5898static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005899#endif
drhc66d5b62008-12-03 22:48:32 +00005900
dan08da86a2009-08-21 17:18:03 +00005901/*
5902** Search for an unused file descriptor that was opened on the database
drh067b92b2020-06-19 15:24:12 +00005903** file (not a journal or super-journal file) identified by pathname
dan08da86a2009-08-21 17:18:03 +00005904** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5905** argument to this function.
5906**
5907** Such a file descriptor may exist if a database connection was closed
5908** but the associated file descriptor could not be closed because some
5909** other file descriptor open on the same file is holding a file-lock.
5910** Refer to comments in the unixClose() function and the lengthy comment
5911** describing "Posix Advisory Locking" at the start of this file for
5912** further details. Also, ticket #4018.
5913**
5914** If a suitable file descriptor is found, then it is returned. If no
5915** such file descriptor is located, -1 is returned.
5916*/
dane946c392009-08-22 11:39:46 +00005917static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5918 UnixUnusedFd *pUnused = 0;
5919
5920 /* Do not search for an unused file descriptor on vxworks. Not because
5921 ** vxworks would not benefit from the change (it might, we're not sure),
5922 ** but because no way to test it is currently available. It is better
5923 ** not to risk breaking vxworks support for the sake of such an obscure
5924 ** feature. */
5925#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005926 struct stat sStat; /* Results of stat() call */
5927
drhc68886b2017-08-18 16:09:52 +00005928 unixEnterMutex();
5929
dan08da86a2009-08-21 17:18:03 +00005930 /* A stat() call may fail for various reasons. If this happens, it is
5931 ** almost certain that an open() call on the same path will also fail.
5932 ** For this reason, if an error occurs in the stat() call here, it is
5933 ** ignored and -1 is returned. The caller will try to open a new file
5934 ** descriptor on the same path, fail, and return an error to SQLite.
5935 **
5936 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005937 ** not searching for a reusable file descriptor are not dire. */
drh095908e2018-08-13 20:46:18 +00005938 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005939 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005940
drh8af6c222010-05-14 12:43:01 +00005941 pInode = inodeList;
5942 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005943 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005944 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005945 }
drh8af6c222010-05-14 12:43:01 +00005946 if( pInode ){
dane946c392009-08-22 11:39:46 +00005947 UnixUnusedFd **pp;
drh095908e2018-08-13 20:46:18 +00005948 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5949 sqlite3_mutex_enter(pInode->pLockMutex);
drh55220a62019-08-06 20:55:06 +00005950 flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
drh8af6c222010-05-14 12:43:01 +00005951 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005952 pUnused = *pp;
5953 if( pUnused ){
5954 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005955 }
drh095908e2018-08-13 20:46:18 +00005956 sqlite3_mutex_leave(pInode->pLockMutex);
dan08da86a2009-08-21 17:18:03 +00005957 }
dan08da86a2009-08-21 17:18:03 +00005958 }
drhc68886b2017-08-18 16:09:52 +00005959 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005960#endif /* if !OS_VXWORKS */
5961 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005962}
danielk197717b90b52008-06-06 11:11:25 +00005963
5964/*
dan1bf4ca72016-08-11 18:05:47 +00005965** Find the mode, uid and gid of file zFile.
5966*/
5967static int getFileMode(
5968 const char *zFile, /* File name */
5969 mode_t *pMode, /* OUT: Permissions of zFile */
5970 uid_t *pUid, /* OUT: uid of zFile. */
5971 gid_t *pGid /* OUT: gid of zFile. */
5972){
5973 struct stat sStat; /* Output of stat() on database file */
5974 int rc = SQLITE_OK;
5975 if( 0==osStat(zFile, &sStat) ){
5976 *pMode = sStat.st_mode & 0777;
5977 *pUid = sStat.st_uid;
5978 *pGid = sStat.st_gid;
5979 }else{
5980 rc = SQLITE_IOERR_FSTAT;
5981 }
5982 return rc;
5983}
5984
5985/*
danddb0ac42010-07-14 14:48:58 +00005986** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005987** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005988** and a value suitable for passing as the third argument to open(2) is
5989** written to *pMode. If an IO error occurs, an SQLite error code is
5990** returned and the value of *pMode is not modified.
5991**
peter.d.reid60ec9142014-09-06 16:39:46 +00005992** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005993** an indication to robust_open() to create the file using
5994** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5995** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005996** this function queries the file-system for the permissions on the
5997** corresponding database file and sets *pMode to this value. Whenever
5998** possible, WAL and journal files are created using the same permissions
5999** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00006000**
6001** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
6002** original filename is unavailable. But 8_3_NAMES is only used for
6003** FAT filesystems and permissions do not matter there, so just use
drh1116b172019-09-25 10:36:31 +00006004** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
danddb0ac42010-07-14 14:48:58 +00006005*/
6006static int findCreateFileMode(
6007 const char *zPath, /* Path of file (possibly) being created */
6008 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00006009 mode_t *pMode, /* OUT: Permissions to open file with */
6010 uid_t *pUid, /* OUT: uid to set on the file */
6011 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00006012){
6013 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00006014 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00006015 *pUid = 0;
6016 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00006017 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00006018 char zDb[MAX_PATHNAME+1]; /* Database file path */
6019 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00006020
dana0c989d2010-11-05 18:07:37 +00006021 /* zPath is a path to a WAL or journal file. The following block derives
6022 ** the path to the associated database file from zPath. This block handles
6023 ** the following naming conventions:
6024 **
6025 ** "<path to db>-journal"
6026 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00006027 ** "<path to db>-journalNN"
6028 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00006029 **
drhd337c5b2011-10-20 18:23:35 +00006030 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00006031 ** used by the test_multiplex.c module.
drh577f0a12022-03-09 12:20:40 +00006032 **
6033 ** In normal operation, the journal file name will always contain
6034 ** a '-' character. However in 8+3 filename mode, or if a corrupt
6035 ** rollback journal specifies a super-journal with a goofy name, then
6036 ** the '-' might be missing or the '-' might be the first character in
6037 ** the filename. In that case, just return SQLITE_OK with *pMode==0.
dana0c989d2010-11-05 18:07:37 +00006038 */
drh577f0a12022-03-09 12:20:40 +00006039 nDb = sqlite3Strlen30(zPath) - 1;
6040 while( nDb>0 && zPath[nDb]!='.' ){
6041 if( zPath[nDb]=='-' ){
6042 memcpy(zDb, zPath, nDb);
6043 zDb[nDb] = '\0';
6044 rc = getFileMode(zDb, pMode, pUid, pGid);
6045 break;
6046 }
drhc47167a2011-10-05 15:26:13 +00006047 nDb--;
6048 }
danddb0ac42010-07-14 14:48:58 +00006049 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
6050 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00006051 }else if( flags & SQLITE_OPEN_URI ){
6052 /* If this is a main database file and the file was opened using a URI
6053 ** filename, check for the "modeof" parameter. If present, interpret
6054 ** its value as a filename and try to copy the mode, uid and gid from
6055 ** that file. */
6056 const char *z = sqlite3_uri_parameter(zPath, "modeof");
6057 if( z ){
6058 rc = getFileMode(z, pMode, pUid, pGid);
6059 }
danddb0ac42010-07-14 14:48:58 +00006060 }
6061 return rc;
6062}
6063
6064/*
danielk1977ad94b582007-08-20 06:44:22 +00006065** Open the file zPath.
6066**
danielk1977b4b47412007-08-17 15:53:36 +00006067** Previously, the SQLite OS layer used three functions in place of this
6068** one:
6069**
6070** sqlite3OsOpenReadWrite();
6071** sqlite3OsOpenReadOnly();
6072** sqlite3OsOpenExclusive();
6073**
6074** These calls correspond to the following combinations of flags:
6075**
6076** ReadWrite() -> (READWRITE | CREATE)
6077** ReadOnly() -> (READONLY)
6078** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
6079**
6080** The old OpenExclusive() accepted a boolean argument - "delFlag". If
6081** true, the file was configured to be automatically deleted when the
6082** file handle closed. To achieve the same effect using this new
6083** interface, add the DELETEONCLOSE flag to those specified above for
6084** OpenExclusive().
6085*/
6086static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00006087 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
6088 const char *zPath, /* Pathname of file to be opened */
6089 sqlite3_file *pFile, /* The file descriptor to be filled in */
6090 int flags, /* Input flags to control the opening */
6091 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00006092){
dan08da86a2009-08-21 17:18:03 +00006093 unixFile *p = (unixFile *)pFile;
6094 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00006095 int openFlags = 0; /* Flags to pass to open() */
drhc398c652019-11-22 00:42:01 +00006096 int eType = flags&0x0FFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00006097 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00006098 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00006099 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00006100
6101 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
6102 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
6103 int isCreate = (flags & SQLITE_OPEN_CREATE);
6104 int isReadonly = (flags & SQLITE_OPEN_READONLY);
6105 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00006106#if SQLITE_ENABLE_LOCKING_STYLE
6107 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
6108#endif
drh3d4435b2011-08-26 20:55:50 +00006109#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6110 struct statfs fsInfo;
6111#endif
danielk1977b4b47412007-08-17 15:53:36 +00006112
drh067b92b2020-06-19 15:24:12 +00006113 /* If creating a super- or main-file journal, this function will open
danielk1977fee2d252007-08-18 10:59:19 +00006114 ** a file-descriptor on the directory too. The first time unixSync()
6115 ** is called the directory file descriptor will be fsync()ed and close()d.
6116 */
drha803a2c2017-12-13 20:02:29 +00006117 int isNewJrnl = (isCreate && (
drhccb21132020-06-19 11:34:57 +00006118 eType==SQLITE_OPEN_SUPER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00006119 || eType==SQLITE_OPEN_MAIN_JOURNAL
6120 || eType==SQLITE_OPEN_WAL
6121 ));
danielk1977fee2d252007-08-18 10:59:19 +00006122
danielk197717b90b52008-06-06 11:11:25 +00006123 /* If argument zPath is a NULL pointer, this function is required to open
6124 ** a temporary file. Use this buffer to store the file name in.
6125 */
drhc02a43a2012-01-10 23:18:38 +00006126 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00006127 const char *zName = zPath;
6128
danielk1977fee2d252007-08-18 10:59:19 +00006129 /* Check the following statements are true:
6130 **
6131 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
6132 ** (b) if CREATE is set, then READWRITE must also be set, and
6133 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00006134 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00006135 */
danielk1977b4b47412007-08-17 15:53:36 +00006136 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00006137 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00006138 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00006139 assert(isDelete==0 || isCreate);
6140
drh067b92b2020-06-19 15:24:12 +00006141 /* The main DB, main journal, WAL file and super-journal are never
danddb0ac42010-07-14 14:48:58 +00006142 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00006143 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
6144 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
drhccb21132020-06-19 11:34:57 +00006145 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006146 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00006147
danielk1977fee2d252007-08-18 10:59:19 +00006148 /* Assert that the upper layer has set one of the "file-type" flags. */
6149 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
6150 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
drhccb21132020-06-19 11:34:57 +00006151 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00006152 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00006153 );
6154
drhb00d8622014-01-01 15:18:36 +00006155 /* Detect a pid change and reset the PRNG. There is a race condition
6156 ** here such that two or more threads all trying to open databases at
6157 ** the same instant might all reset the PRNG. But multiple resets
6158 ** are harmless.
6159 */
drh5ac93652015-03-21 20:59:43 +00006160 if( randomnessPid!=osGetpid(0) ){
6161 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00006162 sqlite3_randomness(0,0);
6163 }
dan08da86a2009-08-21 17:18:03 +00006164 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00006165
drhf81b40a2021-10-23 22:11:18 +00006166#ifdef SQLITE_ASSERT_NO_FILES
6167 /* Applications that never read or write a persistent disk files */
6168 assert( zName==0 );
6169#endif
6170
dan08da86a2009-08-21 17:18:03 +00006171 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00006172 UnixUnusedFd *pUnused;
6173 pUnused = findReusableFd(zName, flags);
6174 if( pUnused ){
6175 fd = pUnused->fd;
6176 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006177 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00006178 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006179 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00006180 }
6181 }
drhc68886b2017-08-18 16:09:52 +00006182 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00006183
6184 /* Database filenames are double-zero terminated if they are not
6185 ** URIs with parameters. Hence, they can always be passed into
6186 ** sqlite3_uri_parameter(). */
6187 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
6188
dan08da86a2009-08-21 17:18:03 +00006189 }else if( !zName ){
6190 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00006191 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00006192 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00006193 if( rc!=SQLITE_OK ){
6194 return rc;
6195 }
6196 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00006197
6198 /* Generated temporary filenames are always double-zero terminated
6199 ** for use by sqlite3_uri_parameter(). */
6200 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00006201 }
6202
dan08da86a2009-08-21 17:18:03 +00006203 /* Determine the value of the flags parameter passed to POSIX function
6204 ** open(). These must be calculated even if open() is not called, as
6205 ** they may be stored as part of the file handle and used by the
6206 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00006207 if( isReadonly ) openFlags |= O_RDONLY;
6208 if( isReadWrite ) openFlags |= O_RDWR;
6209 if( isCreate ) openFlags |= O_CREAT;
6210 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
drhc398c652019-11-22 00:42:01 +00006211 openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
danielk1977b4b47412007-08-17 15:53:36 +00006212
danielk1977b4b47412007-08-17 15:53:36 +00006213 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00006214 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00006215 uid_t uid; /* Userid for the file */
6216 gid_t gid; /* Groupid for the file */
6217 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00006218 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006219 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00006220 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006221 return rc;
6222 }
drhad4f1e52011-03-04 15:43:57 +00006223 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00006224 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00006225 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00006226 if( fd<0 ){
6227 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6228 /* If unable to create a journal because the directory is not
6229 ** writable, change the error code to indicate that. */
6230 rc = SQLITE_READONLY_DIRECTORY;
6231 }else if( errno!=EISDIR && isReadWrite ){
6232 /* Failed to open the file for read/write access. Try read-only. */
6233 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6234 openFlags &= ~(O_RDWR|O_CREAT);
6235 flags |= SQLITE_OPEN_READONLY;
6236 openFlags |= O_RDONLY;
6237 isReadonly = 1;
6238 fd = robust_open(zName, openFlags, openMode);
6239 }
dan08da86a2009-08-21 17:18:03 +00006240 }
6241 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00006242 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6243 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00006244 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00006245 }
drhac7c3ac2012-02-11 19:23:48 +00006246
drh1116b172019-09-25 10:36:31 +00006247 /* The owner of the rollback journal or WAL file should always be the
6248 ** same as the owner of the database file. Try to ensure that this is
6249 ** the case. The chown() system call will be a no-op if the current
6250 ** process lacks root privileges, be we should at least try. Without
6251 ** this step, if a root process opens a database file, it can leave
6252 ** behinds a journal/WAL that is owned by root and hence make the
6253 ** database inaccessible to unprivileged processes.
6254 **
drhedf8a7b2019-09-25 11:49:36 +00006255 ** If openMode==0, then that means uid and gid are not set correctly
drh1116b172019-09-25 10:36:31 +00006256 ** (probably because SQLite is configured to use 8+3 filename mode) and
6257 ** in that case we do not want to attempt the chown().
drhac7c3ac2012-02-11 19:23:48 +00006258 */
drhedf8a7b2019-09-25 11:49:36 +00006259 if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
drh6226ca22015-11-24 15:06:28 +00006260 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00006261 }
danielk1977b4b47412007-08-17 15:53:36 +00006262 }
dan08da86a2009-08-21 17:18:03 +00006263 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00006264 if( pOutFlags ){
6265 *pOutFlags = flags;
6266 }
6267
drhc68886b2017-08-18 16:09:52 +00006268 if( p->pPreallocatedUnused ){
6269 p->pPreallocatedUnused->fd = fd;
drh55220a62019-08-06 20:55:06 +00006270 p->pPreallocatedUnused->flags =
6271 flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
dane946c392009-08-22 11:39:46 +00006272 }
6273
danielk1977b4b47412007-08-17 15:53:36 +00006274 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00006275#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006276 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00006277#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6278 zPath = sqlite3_mprintf("%s", zName);
6279 if( zPath==0 ){
6280 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00006281 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00006282 }
chw97185482008-11-17 08:05:31 +00006283#else
drh036ac7f2011-08-08 23:18:05 +00006284 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00006285#endif
danielk1977b4b47412007-08-17 15:53:36 +00006286 }
drh41022642008-11-21 00:24:42 +00006287#if SQLITE_ENABLE_LOCKING_STYLE
6288 else{
dan08da86a2009-08-21 17:18:03 +00006289 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00006290 }
6291#endif
drh7ed97b92010-01-20 13:07:21 +00006292
6293#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00006294 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00006295 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00006296 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006297 return SQLITE_IOERR_ACCESS;
6298 }
6299 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6300 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6301 }
drh4bf66fd2015-02-19 02:43:02 +00006302 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6303 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6304 }
drh7ed97b92010-01-20 13:07:21 +00006305#endif
drhc02a43a2012-01-10 23:18:38 +00006306
6307 /* Set up appropriate ctrlFlags */
6308 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6309 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00006310 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00006311 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00006312 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00006313 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6314
drh7ed97b92010-01-20 13:07:21 +00006315#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00006316#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00006317 isAutoProxy = 1;
6318#endif
6319 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00006320 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6321 int useProxy = 0;
6322
dan08da86a2009-08-21 17:18:03 +00006323 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6324 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00006325 if( envforce!=NULL ){
6326 useProxy = atoi(envforce)>0;
6327 }else{
aswiftaebf4132008-11-21 00:10:35 +00006328 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6329 }
6330 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006331 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006332 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006333 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006334 if( rc!=SQLITE_OK ){
6335 /* Use unixClose to clean up the resources added in fillInUnixFile
6336 ** and clear all the structure's references. Specifically,
6337 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6338 */
6339 unixClose(pFile);
6340 return rc;
6341 }
aswiftaebf4132008-11-21 00:10:35 +00006342 }
dane946c392009-08-22 11:39:46 +00006343 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006344 }
6345 }
6346#endif
6347
dan3ed0f1c2017-09-14 21:12:07 +00006348 assert( zPath==0 || zPath[0]=='/'
drhccb21132020-06-19 11:34:57 +00006349 || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
dan3ed0f1c2017-09-14 21:12:07 +00006350 );
drhc02a43a2012-01-10 23:18:38 +00006351 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6352
dane946c392009-08-22 11:39:46 +00006353open_finished:
6354 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006355 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006356 }
6357 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006358}
6359
dane946c392009-08-22 11:39:46 +00006360
danielk1977b4b47412007-08-17 15:53:36 +00006361/*
danielk1977fee2d252007-08-18 10:59:19 +00006362** Delete the file at zPath. If the dirSync argument is true, fsync()
6363** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006364*/
drh6b9d6dd2008-12-03 19:34:47 +00006365static int unixDelete(
6366 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6367 const char *zPath, /* Name of file to be deleted */
6368 int dirSync /* If true, fsync() directory after deleting file */
6369){
danielk1977fee2d252007-08-18 10:59:19 +00006370 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006371 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006372 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006373 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006374 if( errno==ENOENT
6375#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006376 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006377#endif
6378 ){
dan9fc5b4a2012-11-09 20:17:26 +00006379 rc = SQLITE_IOERR_DELETE_NOENT;
6380 }else{
drhb4308162012-11-09 21:40:02 +00006381 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006382 }
drhb4308162012-11-09 21:40:02 +00006383 return rc;
drh5d4feff2010-07-14 01:45:22 +00006384 }
danielk1977d39fa702008-10-16 13:27:40 +00006385#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006386 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006387 int fd;
drh90315a22011-08-10 01:52:12 +00006388 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006389 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006390 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006391 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006392 }
drh0e9365c2011-03-02 02:08:13 +00006393 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006394 }else{
6395 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006396 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006397 }
6398 }
danielk1977d138dd82008-10-15 16:02:48 +00006399#endif
danielk1977fee2d252007-08-18 10:59:19 +00006400 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006401}
6402
danielk197790949c22007-08-17 16:50:38 +00006403/*
mistachkin48864df2013-03-21 21:20:32 +00006404** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006405** test performed depends on the value of flags:
6406**
6407** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6408** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6409** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6410**
6411** Otherwise return 0.
6412*/
danielk1977861f7452008-06-05 11:39:11 +00006413static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006414 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6415 const char *zPath, /* Path of the file to examine */
6416 int flags, /* What do we want to learn about the zPath file? */
6417 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006418){
danielk1977397d65f2008-11-19 11:35:39 +00006419 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006420 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006421 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006422
drhc398c652019-11-22 00:42:01 +00006423 /* The spec says there are three possible values for flags. But only
6424 ** two of them are actually used */
6425 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
drhd260b5b2015-11-25 18:03:33 +00006426
6427 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006428 struct stat buf;
drh96e8eeb2019-12-26 00:56:50 +00006429 *pResOut = 0==osStat(zPath, &buf) &&
drh09bee572019-12-27 13:30:46 +00006430 (!S_ISREG(buf.st_mode) || buf.st_size>0);
drh0933aad2019-11-18 17:46:38 +00006431 }else{
drhc398c652019-11-22 00:42:01 +00006432 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006433 }
danielk1977861f7452008-06-05 11:39:11 +00006434 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006435}
6436
danielk1977b4b47412007-08-17 15:53:36 +00006437/*
drhe8346d02022-05-11 16:46:27 +00006438** A pathname under construction
drh7f42dcd2020-11-16 18:45:21 +00006439*/
drhe8346d02022-05-11 16:46:27 +00006440typedef struct DbPath DbPath;
6441struct DbPath {
6442 int rc; /* Non-zero following any error */
6443 int nSymlink; /* Number of symlinks resolved */
6444 char *zOut; /* Write the pathname here */
6445 int nOut; /* Bytes of space available to zOut[] */
6446 int nUsed; /* Bytes of zOut[] currently being used */
6447};
6448
6449/* Forward reference */
6450static void appendAllPathElements(DbPath*,const char*);
6451
6452/*
6453** Append a single path element to the DbPath under construction
6454*/
6455static void appendOnePathElement(
6456 DbPath *pPath, /* Path under construction, to which to append zName */
6457 const char *zName, /* Name to append to pPath. Not zero-terminated */
6458 int nName /* Number of significant bytes in zName */
6459){
6460 assert( nName>0 );
6461 assert( zName!=0 );
6462 if( zName[0]=='.' ){
6463 if( nName==1 ) return;
6464 if( zName[1]=='.' && nName==2 ){
dan2e777342023-01-10 14:31:56 +00006465 if( pPath->nUsed>1 ){
6466 assert( pPath->zOut[0]=='/' );
6467 while( pPath->zOut[--pPath->nUsed]!='/' ){}
drhe8346d02022-05-11 16:46:27 +00006468 }
drhe8346d02022-05-11 16:46:27 +00006469 return;
6470 }
6471 }
6472 if( pPath->nUsed + nName + 2 >= pPath->nOut ){
6473 pPath->rc = SQLITE_ERROR;
6474 return;
6475 }
6476 pPath->zOut[pPath->nUsed++] = '/';
6477 memcpy(&pPath->zOut[pPath->nUsed], zName, nName);
6478 pPath->nUsed += nName;
6479#if defined(HAVE_READLINK) && defined(HAVE_LSTAT)
6480 if( pPath->rc==SQLITE_OK ){
6481 const char *zIn;
6482 struct stat buf;
6483 pPath->zOut[pPath->nUsed] = 0;
6484 zIn = pPath->zOut;
6485 if( osLstat(zIn, &buf)!=0 ){
6486 if( errno!=ENOENT ){
6487 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
6488 }
6489 }else if( S_ISLNK(buf.st_mode) ){
6490 ssize_t got;
6491 char zLnk[SQLITE_MAX_PATHLEN+2];
6492 if( pPath->nSymlink++ > SQLITE_MAX_SYMLINK ){
6493 pPath->rc = SQLITE_CANTOPEN_BKPT;
6494 return;
6495 }
drhb302c062022-05-11 17:45:50 +00006496 got = osReadlink(zIn, zLnk, sizeof(zLnk)-2);
drhb8b2d9c2022-05-17 15:11:57 +00006497 if( got<=0 || got>=(ssize_t)sizeof(zLnk)-2 ){
drhe8346d02022-05-11 16:46:27 +00006498 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
6499 return;
6500 }
6501 zLnk[got] = 0;
6502 if( zLnk[0]=='/' ){
6503 pPath->nUsed = 0;
6504 }else{
6505 pPath->nUsed -= nName + 1;
6506 }
6507 appendAllPathElements(pPath, zLnk);
6508 }
6509 }
6510#endif
drh7f42dcd2020-11-16 18:45:21 +00006511}
6512
6513/*
drhe8346d02022-05-11 16:46:27 +00006514** Append all path elements in zPath to the DbPath under construction.
danielk1977b4b47412007-08-17 15:53:36 +00006515*/
drhe8346d02022-05-11 16:46:27 +00006516static void appendAllPathElements(
6517 DbPath *pPath, /* Path under construction, to which to append zName */
6518 const char *zPath /* Path to append to pPath. Is zero-terminated */
danielk1977adfb9b02007-09-17 07:02:56 +00006519){
drhe8346d02022-05-11 16:46:27 +00006520 int i = 0;
6521 int j = 0;
6522 do{
6523 while( zPath[i] && zPath[i]!='/' ){ i++; }
6524 if( i>j ){
6525 appendOnePathElement(pPath, &zPath[j], i-j);
danielk1977b4b47412007-08-17 15:53:36 +00006526 }
drhe8346d02022-05-11 16:46:27 +00006527 j = i+1;
6528 }while( zPath[i++] );
danielk1977b4b47412007-08-17 15:53:36 +00006529}
6530
dane88ec182016-01-25 17:04:48 +00006531/*
6532** Turn a relative pathname into a full pathname. The relative path
6533** is stored as a nul-terminated string in the buffer pointed to by
6534** zPath.
6535**
6536** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6537** (in this case, MAX_PATHNAME bytes). The full-path is written to
6538** this buffer before returning.
6539*/
6540static int unixFullPathname(
6541 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6542 const char *zPath, /* Possibly relative input path */
6543 int nOut, /* Size of output buffer in bytes */
6544 char *zOut /* Output buffer */
6545){
drhe8346d02022-05-11 16:46:27 +00006546 DbPath path;
drhb8b2d9c2022-05-17 15:11:57 +00006547 UNUSED_PARAMETER(pVfs);
drhe8346d02022-05-11 16:46:27 +00006548 path.rc = 0;
6549 path.nUsed = 0;
6550 path.nSymlink = 0;
6551 path.nOut = nOut;
6552 path.zOut = zOut;
6553 if( zPath[0]!='/' ){
6554 char zPwd[SQLITE_MAX_PATHLEN+2];
6555 if( osGetcwd(zPwd, sizeof(zPwd)-2)==0 ){
6556 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
dancaf6b152016-01-25 18:05:49 +00006557 }
drhe8346d02022-05-11 16:46:27 +00006558 appendAllPathElements(&path, zPwd);
6559 }
6560 appendAllPathElements(&path, zPath);
6561 zOut[path.nUsed] = 0;
6562 if( path.rc || path.nUsed<2 ) return SQLITE_CANTOPEN_BKPT;
6563 if( path.nSymlink ) return SQLITE_OK_SYMLINK;
6564 return SQLITE_OK;
dane88ec182016-01-25 17:04:48 +00006565}
6566
drh761df872006-12-21 01:29:22 +00006567#ifndef SQLITE_OMIT_LOAD_EXTENSION
6568/*
6569** Interfaces for opening a shared library, finding entry points
6570** within the shared library, and closing the shared library.
6571*/
6572#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006573static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6574 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006575 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6576}
danielk197795c8a542007-09-01 06:51:27 +00006577
6578/*
6579** SQLite calls this function immediately after a call to unixDlSym() or
6580** unixDlOpen() fails (returns a null pointer). If a more detailed error
6581** message is available, it is written to zBufOut. If no error message
6582** is available, zBufOut is left unmodified and SQLite uses a default
6583** error message.
6584*/
danielk1977397d65f2008-11-19 11:35:39 +00006585static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006586 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006587 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006588 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006589 zErr = dlerror();
6590 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006591 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006592 }
drh6c7d5c52008-11-21 20:32:33 +00006593 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006594}
drh1875f7a2008-12-08 18:19:17 +00006595static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6596 /*
6597 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6598 ** cast into a pointer to a function. And yet the library dlsym() routine
6599 ** returns a void* which is really a pointer to a function. So how do we
6600 ** use dlsym() with -pedantic-errors?
6601 **
6602 ** Variable x below is defined to be a pointer to a function taking
6603 ** parameters void* and const char* and returning a pointer to a function.
6604 ** We initialize x by assigning it a pointer to the dlsym() function.
6605 ** (That assignment requires a cast.) Then we call the function that
6606 ** x points to.
6607 **
6608 ** This work-around is unlikely to work correctly on any system where
6609 ** you really cannot cast a function pointer into void*. But then, on the
6610 ** other hand, dlsym() will not work on such a system either, so we have
6611 ** not really lost anything.
6612 */
6613 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006614 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006615 x = (void(*(*)(void*,const char*))(void))dlsym;
6616 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006617}
danielk1977397d65f2008-11-19 11:35:39 +00006618static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6619 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006620 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006621}
danielk1977b4b47412007-08-17 15:53:36 +00006622#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6623 #define unixDlOpen 0
6624 #define unixDlError 0
6625 #define unixDlSym 0
6626 #define unixDlClose 0
6627#endif
6628
6629/*
danielk197790949c22007-08-17 16:50:38 +00006630** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006631*/
danielk1977397d65f2008-11-19 11:35:39 +00006632static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6633 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006634 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006635
drhbbd42a62004-05-22 17:41:58 +00006636 /* We have to initialize zBuf to prevent valgrind from reporting
6637 ** errors. The reports issued by valgrind are incorrect - we would
6638 ** prefer that the randomness be increased by making use of the
6639 ** uninitialized space in zBuf - but valgrind errors tend to worry
6640 ** some users. Rather than argue, it seems easier just to initialize
6641 ** the whole array and silence valgrind, even if that means less randomness
6642 ** in the random seed.
6643 **
6644 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006645 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006646 ** tests repeatable.
6647 */
danielk1977b4b47412007-08-17 15:53:36 +00006648 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006649 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006650#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006651 {
drhb00d8622014-01-01 15:18:36 +00006652 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006653 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006654 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006655 time_t t;
6656 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006657 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006658 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6659 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6660 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006661 }else{
drhc18b4042012-02-10 03:10:27 +00006662 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006663 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006664 }
drhbbd42a62004-05-22 17:41:58 +00006665 }
6666#endif
drh72cbd072008-10-14 17:58:38 +00006667 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006668}
6669
danielk1977b4b47412007-08-17 15:53:36 +00006670
drhbbd42a62004-05-22 17:41:58 +00006671/*
6672** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006673** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006674** The return value is the number of microseconds of sleep actually
6675** requested from the underlying operating system, a number which
6676** might be greater than or equal to the argument, but not less
6677** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006678*/
danielk1977397d65f2008-11-19 11:35:39 +00006679static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drha42281a2022-11-30 13:44:31 +00006680#if OS_VXWORKS || _POSIX_C_SOURCE >= 199309L
chw97185482008-11-17 08:05:31 +00006681 struct timespec sp;
6682
6683 sp.tv_sec = microseconds / 1000000;
6684 sp.tv_nsec = (microseconds % 1000000) * 1000;
6685 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006686 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006687 return microseconds;
6688#elif defined(HAVE_USLEEP) && HAVE_USLEEP
drhddcfe922020-09-15 12:29:35 +00006689 if( microseconds>=1000000 ) sleep(microseconds/1000000);
6690 if( microseconds%1000000 ) usleep(microseconds%1000000);
drhd43fe202009-03-01 22:29:20 +00006691 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006692 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006693#else
danielk1977b4b47412007-08-17 15:53:36 +00006694 int seconds = (microseconds+999999)/1000000;
6695 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006696 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006697 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006698#endif
drh88f474a2006-01-02 20:00:12 +00006699}
6700
6701/*
drh6b9d6dd2008-12-03 19:34:47 +00006702** The following variable, if set to a non-zero value, is interpreted as
6703** the number of seconds since 1970 and is used to set the result of
6704** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006705*/
6706#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006707int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006708#endif
6709
6710/*
drhb7e8ea22010-05-03 14:32:30 +00006711** Find the current time (in Universal Coordinated Time). Write into *piNow
6712** the current time and date as a Julian Day number times 86_400_000. In
6713** other words, write into *piNow the number of milliseconds since the Julian
6714** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6715** proleptic Gregorian calendar.
6716**
drh31702252011-10-12 23:13:43 +00006717** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6718** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006719*/
6720static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6721 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006722 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006723#if defined(NO_GETTOD)
6724 time_t t;
6725 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006726 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006727#elif OS_VXWORKS
6728 struct timespec sNow;
6729 clock_gettime(CLOCK_REALTIME, &sNow);
6730 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6731#else
6732 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006733 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6734 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006735#endif
6736
6737#ifdef SQLITE_TEST
6738 if( sqlite3_current_time ){
6739 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6740 }
6741#endif
6742 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006743 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006744}
6745
drhc3dfa5e2016-01-22 19:44:03 +00006746#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006747/*
drhbbd42a62004-05-22 17:41:58 +00006748** Find the current time (in Universal Coordinated Time). Write the
6749** current time and date as a Julian Day number into *prNow and
6750** return 0. Return 1 if the time and date cannot be found.
6751*/
danielk1977397d65f2008-11-19 11:35:39 +00006752static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006753 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006754 int rc;
drhff828942010-06-26 21:34:06 +00006755 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006756 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006757 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006758 return rc;
drhbbd42a62004-05-22 17:41:58 +00006759}
drh5337dac2015-11-25 15:15:03 +00006760#else
6761# define unixCurrentTime 0
6762#endif
danielk1977b4b47412007-08-17 15:53:36 +00006763
drh6b9d6dd2008-12-03 19:34:47 +00006764/*
drh1b9f2142016-03-17 16:01:23 +00006765** The xGetLastError() method is designed to return a better
6766** low-level error message when operating-system problems come up
6767** during SQLite operation. Only the integer return code is currently
6768** used.
drh6b9d6dd2008-12-03 19:34:47 +00006769*/
danielk1977397d65f2008-11-19 11:35:39 +00006770static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6771 UNUSED_PARAMETER(NotUsed);
6772 UNUSED_PARAMETER(NotUsed2);
6773 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006774 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006775}
6776
drhf2424c52010-04-26 00:04:55 +00006777
6778/*
drh734c9862008-11-28 15:37:20 +00006779************************ End of sqlite3_vfs methods ***************************
6780******************************************************************************/
6781
drh715ff302008-12-03 22:32:44 +00006782/******************************************************************************
6783************************** Begin Proxy Locking ********************************
6784**
6785** Proxy locking is a "uber-locking-method" in this sense: It uses the
6786** other locking methods on secondary lock files. Proxy locking is a
6787** meta-layer over top of the primitive locking implemented above. For
6788** this reason, the division that implements of proxy locking is deferred
6789** until late in the file (here) after all of the other I/O methods have
6790** been defined - so that the primitive locking methods are available
6791** as services to help with the implementation of proxy locking.
6792**
6793****
6794**
6795** The default locking schemes in SQLite use byte-range locks on the
6796** database file to coordinate safe, concurrent access by multiple readers
6797** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6798** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6799** as POSIX read & write locks over fixed set of locations (via fsctl),
6800** on AFP and SMB only exclusive byte-range locks are available via fsctl
6801** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6802** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6803** address in the shared range is taken for a SHARED lock, the entire
6804** shared range is taken for an EXCLUSIVE lock):
6805**
drhf2f105d2012-08-20 15:53:54 +00006806** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006807** RESERVED_BYTE 0x40000001
6808** SHARED_RANGE 0x40000002 -> 0x40000200
6809**
6810** This works well on the local file system, but shows a nearly 100x
6811** slowdown in read performance on AFP because the AFP client disables
6812** the read cache when byte-range locks are present. Enabling the read
6813** cache exposes a cache coherency problem that is present on all OS X
6814** supported network file systems. NFS and AFP both observe the
6815** close-to-open semantics for ensuring cache coherency
6816** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6817** address the requirements for concurrent database access by multiple
6818** readers and writers
6819** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6820**
6821** To address the performance and cache coherency issues, proxy file locking
6822** changes the way database access is controlled by limiting access to a
6823** single host at a time and moving file locks off of the database file
6824** and onto a proxy file on the local file system.
6825**
6826**
6827** Using proxy locks
6828** -----------------
6829**
6830** C APIs
6831**
drh4bf66fd2015-02-19 02:43:02 +00006832** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006833** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006834** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6835** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006836**
6837**
6838** SQL pragmas
6839**
6840** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6841** PRAGMA [database.]lock_proxy_file
6842**
6843** Specifying ":auto:" means that if there is a conch file with a matching
6844** host ID in it, the proxy path in the conch file will be used, otherwise
6845** a proxy path based on the user's temp dir
6846** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6847** actual proxy file name is generated from the name and path of the
6848** database file. For example:
6849**
6850** For database path "/Users/me/foo.db"
6851** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6852**
6853** Once a lock proxy is configured for a database connection, it can not
6854** be removed, however it may be switched to a different proxy path via
6855** the above APIs (assuming the conch file is not being held by another
6856** connection or process).
6857**
6858**
6859** How proxy locking works
6860** -----------------------
6861**
6862** Proxy file locking relies primarily on two new supporting files:
6863**
6864** * conch file to limit access to the database file to a single host
6865** at a time
6866**
6867** * proxy file to act as a proxy for the advisory locks normally
6868** taken on the database
6869**
6870** The conch file - to use a proxy file, sqlite must first "hold the conch"
6871** by taking an sqlite-style shared lock on the conch file, reading the
6872** contents and comparing the host's unique host ID (see below) and lock
6873** proxy path against the values stored in the conch. The conch file is
6874** stored in the same directory as the database file and the file name
6875** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006876** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006877** host ID and/or proxy path, then the lock is escalated to an exclusive
6878** lock and the conch file contents is updated with the host ID and proxy
6879** path and the lock is downgraded to a shared lock again. If the conch
6880** is held by another process (with a shared lock), the exclusive lock
6881** will fail and SQLITE_BUSY is returned.
6882**
6883** The proxy file - a single-byte file used for all advisory file locks
6884** normally taken on the database file. This allows for safe sharing
6885** of the database file for multiple readers and writers on the same
6886** host (the conch ensures that they all use the same local lock file).
6887**
drh715ff302008-12-03 22:32:44 +00006888** Requesting the lock proxy does not immediately take the conch, it is
6889** only taken when the first request to lock database file is made.
6890** This matches the semantics of the traditional locking behavior, where
6891** opening a connection to a database file does not take a lock on it.
6892** The shared lock and an open file descriptor are maintained until
6893** the connection to the database is closed.
6894**
6895** The proxy file and the lock file are never deleted so they only need
6896** to be created the first time they are used.
6897**
6898** Configuration options
6899** ---------------------
6900**
6901** SQLITE_PREFER_PROXY_LOCKING
6902**
6903** Database files accessed on non-local file systems are
6904** automatically configured for proxy locking, lock files are
6905** named automatically using the same logic as
6906** PRAGMA lock_proxy_file=":auto:"
6907**
6908** SQLITE_PROXY_DEBUG
6909**
6910** Enables the logging of error messages during host id file
6911** retrieval and creation
6912**
drh715ff302008-12-03 22:32:44 +00006913** LOCKPROXYDIR
6914**
6915** Overrides the default directory used for lock proxy files that
6916** are named automatically via the ":auto:" setting
6917**
6918** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6919**
6920** Permissions to use when creating a directory for storing the
6921** lock proxy files, only used when LOCKPROXYDIR is not set.
6922**
6923**
6924** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6925** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6926** force proxy locking to be used for every database file opened, and 0
6927** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006928** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006929** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6930*/
6931
6932/*
6933** Proxy locking is only available on MacOSX
6934*/
drhd2cb50b2009-01-09 21:41:17 +00006935#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006936
drh715ff302008-12-03 22:32:44 +00006937/*
6938** The proxyLockingContext has the path and file structures for the remote
6939** and local proxy files in it
6940*/
6941typedef struct proxyLockingContext proxyLockingContext;
6942struct proxyLockingContext {
6943 unixFile *conchFile; /* Open conch file */
6944 char *conchFilePath; /* Name of the conch file */
6945 unixFile *lockProxy; /* Open proxy lock file */
6946 char *lockProxyPath; /* Name of the proxy lock file */
6947 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006948 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006949 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006950 void *oldLockingContext; /* Original lockingcontext to restore on close */
6951 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6952};
6953
drh7ed97b92010-01-20 13:07:21 +00006954/*
6955** The proxy lock file path for the database at dbPath is written into lPath,
6956** which must point to valid, writable memory large enough for a maxLen length
6957** file path.
drh715ff302008-12-03 22:32:44 +00006958*/
drh715ff302008-12-03 22:32:44 +00006959static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6960 int len;
6961 int dbLen;
6962 int i;
6963
6964#ifdef LOCKPROXYDIR
6965 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6966#else
6967# ifdef _CS_DARWIN_USER_TEMP_DIR
6968 {
drh7ed97b92010-01-20 13:07:21 +00006969 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006970 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006971 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006972 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006973 }
drh7ed97b92010-01-20 13:07:21 +00006974 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006975 }
6976# else
6977 len = strlcpy(lPath, "/tmp/", maxLen);
6978# endif
6979#endif
6980
6981 if( lPath[len-1]!='/' ){
6982 len = strlcat(lPath, "/", maxLen);
6983 }
6984
6985 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006986 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006987 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006988 char c = dbPath[i];
6989 lPath[i+len] = (c=='/')?'_':c;
6990 }
6991 lPath[i+len]='\0';
6992 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006993 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006994 return SQLITE_OK;
6995}
6996
drh7ed97b92010-01-20 13:07:21 +00006997/*
6998 ** Creates the lock file and any missing directories in lockPath
6999 */
7000static int proxyCreateLockPath(const char *lockPath){
7001 int i, len;
7002 char buf[MAXPATHLEN];
7003 int start = 0;
7004
7005 assert(lockPath!=NULL);
7006 /* try to create all the intermediate directories */
7007 len = (int)strlen(lockPath);
7008 buf[0] = lockPath[0];
7009 for( i=1; i<len; i++ ){
7010 if( lockPath[i] == '/' && (i - start > 0) ){
7011 /* only mkdir if leaf dir != "." or "/" or ".." */
7012 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
7013 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
7014 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00007015 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00007016 int err=errno;
7017 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00007018 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00007019 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00007020 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007021 return err;
7022 }
7023 }
7024 }
7025 start=i+1;
7026 }
7027 buf[i] = lockPath[i];
7028 }
drh62aaa6c2015-11-21 17:27:42 +00007029 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007030 return 0;
7031}
7032
drh715ff302008-12-03 22:32:44 +00007033/*
7034** Create a new VFS file descriptor (stored in memory obtained from
7035** sqlite3_malloc) and open the file named "path" in the file descriptor.
7036**
7037** The caller is responsible not only for closing the file descriptor
7038** but also for freeing the memory associated with the file descriptor.
7039*/
drh7ed97b92010-01-20 13:07:21 +00007040static int proxyCreateUnixFile(
7041 const char *path, /* path for the new unixFile */
7042 unixFile **ppFile, /* unixFile created and returned by ref */
7043 int islockfile /* if non zero missing dirs will be created */
7044) {
7045 int fd = -1;
drh715ff302008-12-03 22:32:44 +00007046 unixFile *pNew;
7047 int rc = SQLITE_OK;
drhc398c652019-11-22 00:42:01 +00007048 int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
drh715ff302008-12-03 22:32:44 +00007049 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00007050 int terrno = 0;
7051 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00007052
drh7ed97b92010-01-20 13:07:21 +00007053 /* 1. first try to open/create the file
7054 ** 2. if that fails, and this is a lock file (not-conch), try creating
7055 ** the parent directories and then try again.
7056 ** 3. if that fails, try to open the file read-only
7057 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
7058 */
7059 pUnused = findReusableFd(path, openFlags);
7060 if( pUnused ){
7061 fd = pUnused->fd;
7062 }else{
drhf3cdcdc2015-04-29 16:50:28 +00007063 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00007064 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00007065 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007066 }
7067 }
7068 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00007069 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00007070 terrno = errno;
7071 if( fd<0 && errno==ENOENT && islockfile ){
7072 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00007073 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00007074 }
7075 }
7076 }
7077 if( fd<0 ){
drhc398c652019-11-22 00:42:01 +00007078 openFlags = O_RDONLY | O_NOFOLLOW;
drh8c815d12012-02-13 20:16:37 +00007079 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00007080 terrno = errno;
7081 }
7082 if( fd<0 ){
7083 if( islockfile ){
7084 return SQLITE_BUSY;
7085 }
7086 switch (terrno) {
7087 case EACCES:
7088 return SQLITE_PERM;
7089 case EIO:
7090 return SQLITE_IOERR_LOCK; /* even though it is the conch */
7091 default:
drh9978c972010-02-23 17:36:32 +00007092 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007093 }
7094 }
7095
drhf3cdcdc2015-04-29 16:50:28 +00007096 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00007097 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007098 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007099 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00007100 }
7101 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00007102 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00007103 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00007104 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00007105 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00007106 pUnused->fd = fd;
7107 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00007108 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00007109
drhc02a43a2012-01-10 23:18:38 +00007110 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00007111 if( rc==SQLITE_OK ){
7112 *ppFile = pNew;
7113 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00007114 }
drh7ed97b92010-01-20 13:07:21 +00007115end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00007116 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007117 sqlite3_free(pNew);
7118 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00007119 return rc;
7120}
7121
drh7ed97b92010-01-20 13:07:21 +00007122#ifdef SQLITE_TEST
7123/* simulate multiple hosts by creating unique hostid file paths */
7124int sqlite3_hostid_num = 0;
7125#endif
7126
7127#define PROXY_HOSTIDLEN 16 /* conch file host id length */
7128
drhe4079e12019-09-27 16:33:27 +00007129#if HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00007130/* Not always defined in the headers as it ought to be */
7131extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00007132#endif
drh0ab216a2010-07-02 17:10:40 +00007133
drh7ed97b92010-01-20 13:07:21 +00007134/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
7135** bytes of writable memory.
7136*/
7137static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00007138 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
7139 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe4079e12019-09-27 16:33:27 +00007140#if HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00007141 {
drh4bf66fd2015-02-19 02:43:02 +00007142 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00007143 if( gethostuuid(pHostID, &timeout) ){
7144 int err = errno;
7145 if( pError ){
7146 *pError = err;
7147 }
7148 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00007149 }
drh7ed97b92010-01-20 13:07:21 +00007150 }
drh3d4435b2011-08-26 20:55:50 +00007151#else
7152 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00007153#endif
drh7ed97b92010-01-20 13:07:21 +00007154#ifdef SQLITE_TEST
7155 /* simulate multiple hosts by creating unique hostid file paths */
7156 if( sqlite3_hostid_num != 0){
7157 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
7158 }
7159#endif
7160
7161 return SQLITE_OK;
7162}
7163
7164/* The conch file contains the header, host id and lock file path
7165 */
7166#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7167#define PROXY_HEADERLEN 1 /* conch file header length */
7168#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7169#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7170
7171/*
7172** Takes an open conch file, copies the contents to a new path and then moves
7173** it back. The newly created file's file descriptor is assigned to the
7174** conch file structure and finally the original conch file descriptor is
7175** closed. Returns zero if successful.
7176*/
7177static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
7178 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7179 unixFile *conchFile = pCtx->conchFile;
7180 char tPath[MAXPATHLEN];
7181 char buf[PROXY_MAXCONCHLEN];
7182 char *cPath = pCtx->conchFilePath;
7183 size_t readLen = 0;
7184 size_t pathLen = 0;
7185 char errmsg[64] = "";
7186 int fd = -1;
7187 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00007188 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00007189
7190 /* create a new path by replace the trailing '-conch' with '-break' */
7191 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
7192 if( pathLen>MAXPATHLEN || pathLen<6 ||
7193 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00007194 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00007195 goto end_breaklock;
7196 }
7197 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00007198 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007199 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00007200 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00007201 goto end_breaklock;
7202 }
7203 /* write it out to the temporary break file */
drhc398c652019-11-22 00:42:01 +00007204 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
drh7ed97b92010-01-20 13:07:21 +00007205 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00007206 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007207 goto end_breaklock;
7208 }
drhe562be52011-03-02 18:01:10 +00007209 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00007210 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007211 goto end_breaklock;
7212 }
7213 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00007214 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007215 goto end_breaklock;
7216 }
7217 rc = 0;
7218 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00007219 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007220 conchFile->h = fd;
7221 conchFile->openFlags = O_RDWR | O_CREAT;
7222
7223end_breaklock:
7224 if( rc ){
7225 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00007226 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00007227 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007228 }
7229 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7230 }
7231 return rc;
7232}
7233
7234/* Take the requested lock on the conch file and break a stale lock if the
7235** host id matches.
7236*/
7237static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7238 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7239 unixFile *conchFile = pCtx->conchFile;
7240 int rc = SQLITE_OK;
7241 int nTries = 0;
7242 struct timespec conchModTime;
7243
drh3d4435b2011-08-26 20:55:50 +00007244 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00007245 do {
7246 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7247 nTries ++;
7248 if( rc==SQLITE_BUSY ){
7249 /* If the lock failed (busy):
7250 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7251 * 2nd try: fail if the mod time changed or host id is different, wait
7252 * 10 sec and try again
7253 * 3rd try: break the lock unless the mod time has changed.
7254 */
7255 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007256 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00007257 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007258 return SQLITE_IOERR_LOCK;
7259 }
7260
7261 if( nTries==1 ){
7262 conchModTime = buf.st_mtimespec;
drhddcfe922020-09-15 12:29:35 +00007263 unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/
drh7ed97b92010-01-20 13:07:21 +00007264 continue;
7265 }
7266
7267 assert( nTries>1 );
7268 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7269 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7270 return SQLITE_BUSY;
7271 }
7272
7273 if( nTries==2 ){
7274 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00007275 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007276 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00007277 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007278 return SQLITE_IOERR_LOCK;
7279 }
7280 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7281 /* don't break the lock if the host id doesn't match */
7282 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7283 return SQLITE_BUSY;
7284 }
7285 }else{
7286 /* don't break the lock on short read or a version mismatch */
7287 return SQLITE_BUSY;
7288 }
drhddcfe922020-09-15 12:29:35 +00007289 unixSleep(0,10000000); /* wait 10 sec and try the lock again */
drh7ed97b92010-01-20 13:07:21 +00007290 continue;
7291 }
7292
7293 assert( nTries==3 );
7294 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7295 rc = SQLITE_OK;
7296 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00007297 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00007298 }
7299 if( !rc ){
7300 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7301 }
7302 }
7303 }
7304 } while( rc==SQLITE_BUSY && nTries<3 );
7305
7306 return rc;
7307}
7308
7309/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00007310** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7311** lockPath means that the lockPath in the conch file will be used if the
7312** host IDs match, or a new lock path will be generated automatically
7313** and written to the conch file.
7314*/
7315static int proxyTakeConch(unixFile *pFile){
7316 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7317
drh7ed97b92010-01-20 13:07:21 +00007318 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00007319 return SQLITE_OK;
7320 }else{
7321 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00007322 uuid_t myHostID;
7323 int pError = 0;
7324 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00007325 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00007326 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00007327 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00007328 int createConch = 0;
7329 int hostIdMatch = 0;
7330 int readLen = 0;
7331 int tryOldLockPath = 0;
7332 int forceNewLockPath = 0;
7333
drh308c2a52010-05-14 11:30:18 +00007334 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00007335 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007336 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007337
drh7ed97b92010-01-20 13:07:21 +00007338 rc = proxyGetHostID(myHostID, &pError);
7339 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007340 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007341 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007342 }
drh7ed97b92010-01-20 13:07:21 +00007343 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007344 if( rc!=SQLITE_OK ){
7345 goto end_takeconch;
7346 }
drh7ed97b92010-01-20 13:07:21 +00007347 /* read the existing conch file */
7348 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7349 if( readLen<0 ){
7350 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007351 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007352 rc = SQLITE_IOERR_READ;
7353 goto end_takeconch;
7354 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7355 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7356 /* a short read or version format mismatch means we need to create a new
7357 ** conch file.
7358 */
7359 createConch = 1;
7360 }
7361 /* if the host id matches and the lock path already exists in the conch
7362 ** we'll try to use the path there, if we can't open that path, we'll
7363 ** retry with a new auto-generated path
7364 */
7365 do { /* in case we need to try again for an :auto: named lock file */
7366
7367 if( !createConch && !forceNewLockPath ){
7368 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7369 PROXY_HOSTIDLEN);
7370 /* if the conch has data compare the contents */
7371 if( !pCtx->lockProxyPath ){
7372 /* for auto-named local lock file, just check the host ID and we'll
7373 ** use the local lock file path that's already in there
7374 */
7375 if( hostIdMatch ){
7376 size_t pathLen = (readLen - PROXY_PATHINDEX);
7377
7378 if( pathLen>=MAXPATHLEN ){
7379 pathLen=MAXPATHLEN-1;
7380 }
7381 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7382 lockPath[pathLen] = 0;
7383 tempLockPath = lockPath;
7384 tryOldLockPath = 1;
7385 /* create a copy of the lock path if the conch is taken */
7386 goto end_takeconch;
7387 }
7388 }else if( hostIdMatch
7389 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7390 readLen-PROXY_PATHINDEX)
7391 ){
7392 /* conch host and lock path match */
7393 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007394 }
drh7ed97b92010-01-20 13:07:21 +00007395 }
7396
7397 /* if the conch isn't writable and doesn't match, we can't take it */
7398 if( (conchFile->openFlags&O_RDWR) == 0 ){
7399 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007400 goto end_takeconch;
7401 }
drh7ed97b92010-01-20 13:07:21 +00007402
7403 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007404 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007405 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7406 tempLockPath = lockPath;
7407 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007408 }
drh7ed97b92010-01-20 13:07:21 +00007409
7410 /* update conch with host and path (this will fail if other process
7411 ** has a shared lock already), if the host id matches, use the big
7412 ** stick.
drh715ff302008-12-03 22:32:44 +00007413 */
drh7ed97b92010-01-20 13:07:21 +00007414 futimes(conchFile->h, NULL);
7415 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007416 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007417 /* We are trying for an exclusive lock but another thread in this
7418 ** same process is still holding a shared lock. */
7419 rc = SQLITE_BUSY;
7420 } else {
7421 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007422 }
drh715ff302008-12-03 22:32:44 +00007423 }else{
drh4bf66fd2015-02-19 02:43:02 +00007424 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007425 }
drh7ed97b92010-01-20 13:07:21 +00007426 if( rc==SQLITE_OK ){
7427 char writeBuffer[PROXY_MAXCONCHLEN];
7428 int writeSize = 0;
7429
7430 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7431 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7432 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007433 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7434 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007435 }else{
7436 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7437 }
7438 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007439 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007440 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007441 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007442 /* If we created a new conch file (not just updated the contents of a
7443 ** valid conch file), try to match the permissions of the database
7444 */
7445 if( rc==SQLITE_OK && createConch ){
7446 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007447 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007448 if( err==0 ){
7449 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7450 S_IROTH|S_IWOTH);
7451 /* try to match the database file R/W permissions, ignore failure */
7452#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007453 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007454#else
drhff812312011-02-23 13:33:46 +00007455 do{
drhe562be52011-03-02 18:01:10 +00007456 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007457 }while( rc==(-1) && errno==EINTR );
7458 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007459 int code = errno;
7460 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7461 cmode, code, strerror(code));
7462 } else {
7463 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7464 }
7465 }else{
7466 int code = errno;
7467 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7468 err, code, strerror(code));
7469#endif
7470 }
drh715ff302008-12-03 22:32:44 +00007471 }
7472 }
drh7ed97b92010-01-20 13:07:21 +00007473 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7474
7475 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007476 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007477 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007478 int fd;
drh7ed97b92010-01-20 13:07:21 +00007479 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007480 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007481 }
7482 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007483 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007484 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007485 if( fd>=0 ){
7486 pFile->h = fd;
7487 }else{
drh9978c972010-02-23 17:36:32 +00007488 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007489 during locking */
7490 }
7491 }
7492 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7493 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7494 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7495 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7496 /* we couldn't create the proxy lock file with the old lock file path
7497 ** so try again via auto-naming
7498 */
7499 forceNewLockPath = 1;
7500 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007501 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007502 }
7503 }
7504 if( rc==SQLITE_OK ){
7505 /* Need to make a copy of path if we extracted the value
7506 ** from the conch file or the path was allocated on the stack
7507 */
7508 if( tempLockPath ){
7509 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7510 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007511 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007512 }
7513 }
7514 }
7515 if( rc==SQLITE_OK ){
7516 pCtx->conchHeld = 1;
7517
7518 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7519 afpLockingContext *afpCtx;
7520 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7521 afpCtx->dbPath = pCtx->lockProxyPath;
7522 }
7523 } else {
7524 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7525 }
drh308c2a52010-05-14 11:30:18 +00007526 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7527 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007528 return rc;
drh308c2a52010-05-14 11:30:18 +00007529 } while (1); /* in case we need to retry the :auto: lock file -
7530 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007531 }
7532}
7533
7534/*
7535** If pFile holds a lock on a conch file, then release that lock.
7536*/
7537static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007538 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007539 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7540 unixFile *conchFile; /* Name of the conch file */
7541
7542 pCtx = (proxyLockingContext *)pFile->lockingContext;
7543 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007544 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007545 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007546 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007547 if( pCtx->conchHeld>0 ){
7548 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7549 }
drh715ff302008-12-03 22:32:44 +00007550 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007551 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7552 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007553 return rc;
7554}
7555
7556/*
7557** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007558** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007559** Make *pConchPath point to the new name. Return SQLITE_OK on success
7560** or SQLITE_NOMEM if unable to obtain memory.
7561**
7562** The caller is responsible for ensuring that the allocated memory
7563** space is eventually freed.
7564**
7565** *pConchPath is set to NULL if a memory allocation error occurs.
7566*/
7567static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7568 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007569 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007570 char *conchPath; /* buffer in which to construct conch name */
7571
7572 /* Allocate space for the conch filename and initialize the name to
7573 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007574 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007575 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007576 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007577 }
7578 memcpy(conchPath, dbPath, len+1);
7579
7580 /* now insert a "." before the last / character */
7581 for( i=(len-1); i>=0; i-- ){
7582 if( conchPath[i]=='/' ){
7583 i++;
7584 break;
7585 }
7586 }
7587 conchPath[i]='.';
7588 while ( i<len ){
7589 conchPath[i+1]=dbPath[i];
7590 i++;
7591 }
7592
7593 /* append the "-conch" suffix to the file */
7594 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007595 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007596
7597 return SQLITE_OK;
7598}
7599
7600
7601/* Takes a fully configured proxy locking-style unix file and switches
7602** the local lock file path
7603*/
7604static int switchLockProxyPath(unixFile *pFile, const char *path) {
7605 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7606 char *oldPath = pCtx->lockProxyPath;
7607 int rc = SQLITE_OK;
7608
drh308c2a52010-05-14 11:30:18 +00007609 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007610 return SQLITE_BUSY;
7611 }
7612
7613 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7614 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7615 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7616 return SQLITE_OK;
7617 }else{
7618 unixFile *lockProxy = pCtx->lockProxy;
7619 pCtx->lockProxy=NULL;
7620 pCtx->conchHeld = 0;
7621 if( lockProxy!=NULL ){
7622 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7623 if( rc ) return rc;
7624 sqlite3_free(lockProxy);
7625 }
7626 sqlite3_free(oldPath);
7627 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7628 }
7629
7630 return rc;
7631}
7632
7633/*
7634** pFile is a file that has been opened by a prior xOpen call. dbPath
7635** is a string buffer at least MAXPATHLEN+1 characters in size.
7636**
7637** This routine find the filename associated with pFile and writes it
7638** int dbPath.
7639*/
7640static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007641#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007642 if( pFile->pMethod == &afpIoMethods ){
7643 /* afp style keeps a reference to the db path in the filePath field
7644 ** of the struct */
drhea678832008-12-10 19:26:22 +00007645 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007646 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7647 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007648 } else
drh715ff302008-12-03 22:32:44 +00007649#endif
7650 if( pFile->pMethod == &dotlockIoMethods ){
7651 /* dot lock style uses the locking context to store the dot lock
7652 ** file path */
7653 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7654 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7655 }else{
7656 /* all other styles use the locking context to store the db file path */
7657 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007658 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007659 }
7660 return SQLITE_OK;
7661}
7662
7663/*
7664** Takes an already filled in unix file and alters it so all file locking
7665** will be performed on the local proxy lock file. The following fields
7666** are preserved in the locking context so that they can be restored and
7667** the unix structure properly cleaned up at close time:
7668** ->lockingContext
7669** ->pMethod
7670*/
7671static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7672 proxyLockingContext *pCtx;
7673 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7674 char *lockPath=NULL;
7675 int rc = SQLITE_OK;
7676
drh308c2a52010-05-14 11:30:18 +00007677 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007678 return SQLITE_BUSY;
7679 }
7680 proxyGetDbPathForUnixFile(pFile, dbPath);
7681 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7682 lockPath=NULL;
7683 }else{
7684 lockPath=(char *)path;
7685 }
7686
drh308c2a52010-05-14 11:30:18 +00007687 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007688 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007689
drhf3cdcdc2015-04-29 16:50:28 +00007690 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007691 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007692 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007693 }
7694 memset(pCtx, 0, sizeof(*pCtx));
7695
7696 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7697 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007698 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7699 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7700 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7701 ** (c) the file system is read-only, then enable no-locking access.
7702 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7703 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7704 */
7705 struct statfs fsInfo;
7706 struct stat conchInfo;
7707 int goLockless = 0;
7708
drh99ab3b12011-03-02 15:09:07 +00007709 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007710 int err = errno;
7711 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7712 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7713 }
7714 }
7715 if( goLockless ){
7716 pCtx->conchHeld = -1; /* read only FS/ lockless */
7717 rc = SQLITE_OK;
7718 }
7719 }
drh715ff302008-12-03 22:32:44 +00007720 }
7721 if( rc==SQLITE_OK && lockPath ){
7722 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7723 }
7724
7725 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007726 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7727 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007728 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007729 }
7730 }
7731 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007732 /* all memory is allocated, proxys are created and assigned,
7733 ** switch the locking context and pMethod then return.
7734 */
drh715ff302008-12-03 22:32:44 +00007735 pCtx->oldLockingContext = pFile->lockingContext;
7736 pFile->lockingContext = pCtx;
7737 pCtx->pOldMethod = pFile->pMethod;
7738 pFile->pMethod = &proxyIoMethods;
7739 }else{
7740 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007741 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007742 sqlite3_free(pCtx->conchFile);
7743 }
drhd56b1212010-08-11 06:14:15 +00007744 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007745 sqlite3_free(pCtx->conchFilePath);
7746 sqlite3_free(pCtx);
7747 }
drh308c2a52010-05-14 11:30:18 +00007748 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7749 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007750 return rc;
7751}
7752
7753
7754/*
7755** This routine handles sqlite3_file_control() calls that are specific
7756** to proxy locking.
7757*/
7758static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7759 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007760 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007761 unixFile *pFile = (unixFile*)id;
7762 if( pFile->pMethod == &proxyIoMethods ){
7763 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7764 proxyTakeConch(pFile);
7765 if( pCtx->lockProxyPath ){
7766 *(const char **)pArg = pCtx->lockProxyPath;
7767 }else{
7768 *(const char **)pArg = ":auto: (not held)";
7769 }
7770 } else {
7771 *(const char **)pArg = NULL;
7772 }
7773 return SQLITE_OK;
7774 }
drh4bf66fd2015-02-19 02:43:02 +00007775 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007776 unixFile *pFile = (unixFile*)id;
7777 int rc = SQLITE_OK;
7778 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7779 if( pArg==NULL || (const char *)pArg==0 ){
7780 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007781 /* turn off proxy locking - not supported. If support is added for
7782 ** switching proxy locking mode off then it will need to fail if
7783 ** the journal mode is WAL mode.
7784 */
drh715ff302008-12-03 22:32:44 +00007785 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7786 }else{
7787 /* turn off proxy locking - already off - NOOP */
7788 rc = SQLITE_OK;
7789 }
7790 }else{
7791 const char *proxyPath = (const char *)pArg;
7792 if( isProxyStyle ){
7793 proxyLockingContext *pCtx =
7794 (proxyLockingContext*)pFile->lockingContext;
7795 if( !strcmp(pArg, ":auto:")
7796 || (pCtx->lockProxyPath &&
7797 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7798 ){
7799 rc = SQLITE_OK;
7800 }else{
7801 rc = switchLockProxyPath(pFile, proxyPath);
7802 }
7803 }else{
7804 /* turn on proxy file locking */
7805 rc = proxyTransformUnixFile(pFile, proxyPath);
7806 }
7807 }
7808 return rc;
7809 }
7810 default: {
7811 assert( 0 ); /* The call assures that only valid opcodes are sent */
7812 }
7813 }
drh8616cff2019-07-13 16:15:23 +00007814 /*NOTREACHED*/ assert(0);
drh715ff302008-12-03 22:32:44 +00007815 return SQLITE_ERROR;
7816}
7817
7818/*
7819** Within this division (the proxying locking implementation) the procedures
7820** above this point are all utilities. The lock-related methods of the
7821** proxy-locking sqlite3_io_method object follow.
7822*/
7823
7824
7825/*
7826** This routine checks if there is a RESERVED lock held on the specified
7827** file by this or any other process. If such a lock is held, set *pResOut
7828** to a non-zero value otherwise *pResOut is set to zero. The return value
7829** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7830*/
7831static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7832 unixFile *pFile = (unixFile*)id;
7833 int rc = proxyTakeConch(pFile);
7834 if( rc==SQLITE_OK ){
7835 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007836 if( pCtx->conchHeld>0 ){
7837 unixFile *proxy = pCtx->lockProxy;
7838 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7839 }else{ /* conchHeld < 0 is lockless */
7840 pResOut=0;
7841 }
drh715ff302008-12-03 22:32:44 +00007842 }
7843 return rc;
7844}
7845
7846/*
drh308c2a52010-05-14 11:30:18 +00007847** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007848** of the following:
7849**
7850** (1) SHARED_LOCK
7851** (2) RESERVED_LOCK
7852** (3) PENDING_LOCK
7853** (4) EXCLUSIVE_LOCK
7854**
7855** Sometimes when requesting one lock state, additional lock states
7856** are inserted in between. The locking might fail on one of the later
7857** transitions leaving the lock state different from what it started but
7858** still short of its goal. The following chart shows the allowed
7859** transitions and the inserted intermediate states:
7860**
7861** UNLOCKED -> SHARED
7862** SHARED -> RESERVED
7863** SHARED -> (PENDING) -> EXCLUSIVE
7864** RESERVED -> (PENDING) -> EXCLUSIVE
7865** PENDING -> EXCLUSIVE
7866**
7867** This routine will only increase a lock. Use the sqlite3OsUnlock()
7868** routine to lower a locking level.
7869*/
drh308c2a52010-05-14 11:30:18 +00007870static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007871 unixFile *pFile = (unixFile*)id;
7872 int rc = proxyTakeConch(pFile);
7873 if( rc==SQLITE_OK ){
7874 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007875 if( pCtx->conchHeld>0 ){
7876 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007877 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7878 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007879 }else{
7880 /* conchHeld < 0 is lockless */
7881 }
drh715ff302008-12-03 22:32:44 +00007882 }
7883 return rc;
7884}
7885
7886
7887/*
drh308c2a52010-05-14 11:30:18 +00007888** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007889** must be either NO_LOCK or SHARED_LOCK.
7890**
7891** If the locking level of the file descriptor is already at or below
7892** the requested locking level, this routine is a no-op.
7893*/
drh308c2a52010-05-14 11:30:18 +00007894static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007895 unixFile *pFile = (unixFile*)id;
7896 int rc = proxyTakeConch(pFile);
7897 if( rc==SQLITE_OK ){
7898 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007899 if( pCtx->conchHeld>0 ){
7900 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007901 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7902 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007903 }else{
7904 /* conchHeld < 0 is lockless */
7905 }
drh715ff302008-12-03 22:32:44 +00007906 }
7907 return rc;
7908}
7909
7910/*
7911** Close a file that uses proxy locks.
7912*/
7913static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007914 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007915 unixFile *pFile = (unixFile*)id;
7916 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7917 unixFile *lockProxy = pCtx->lockProxy;
7918 unixFile *conchFile = pCtx->conchFile;
7919 int rc = SQLITE_OK;
7920
7921 if( lockProxy ){
7922 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7923 if( rc ) return rc;
7924 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7925 if( rc ) return rc;
7926 sqlite3_free(lockProxy);
7927 pCtx->lockProxy = 0;
7928 }
7929 if( conchFile ){
7930 if( pCtx->conchHeld ){
7931 rc = proxyReleaseConch(pFile);
7932 if( rc ) return rc;
7933 }
7934 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7935 if( rc ) return rc;
7936 sqlite3_free(conchFile);
7937 }
drhd56b1212010-08-11 06:14:15 +00007938 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007939 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007940 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007941 /* restore the original locking context and pMethod then close it */
7942 pFile->lockingContext = pCtx->oldLockingContext;
7943 pFile->pMethod = pCtx->pOldMethod;
7944 sqlite3_free(pCtx);
7945 return pFile->pMethod->xClose(id);
7946 }
7947 return SQLITE_OK;
7948}
7949
7950
7951
drhd2cb50b2009-01-09 21:41:17 +00007952#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007953/*
7954** The proxy locking style is intended for use with AFP filesystems.
7955** And since AFP is only supported on MacOSX, the proxy locking is also
7956** restricted to MacOSX.
7957**
7958**
7959******************* End of the proxy lock implementation **********************
7960******************************************************************************/
7961
drh734c9862008-11-28 15:37:20 +00007962/*
danielk1977e339d652008-06-28 11:23:00 +00007963** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007964**
7965** This routine registers all VFS implementations for unix-like operating
7966** systems. This routine, and the sqlite3_os_end() routine that follows,
7967** should be the only routines in this file that are visible from other
7968** files.
drh6b9d6dd2008-12-03 19:34:47 +00007969**
7970** This routine is called once during SQLite initialization and by a
7971** single thread. The memory allocation and mutex subsystems have not
7972** necessarily been initialized when this routine is called, and so they
7973** should not be used.
drh153c62c2007-08-24 03:51:33 +00007974*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007975int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007976 /*
7977 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007978 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7979 ** to the "finder" function. (pAppData is a pointer to a pointer because
7980 ** silly C90 rules prohibit a void* from being cast to a function pointer
7981 ** and so we have to go through the intermediate pointer to avoid problems
7982 ** when compiling with -pedantic-errors on GCC.)
7983 **
7984 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007985 ** finder-function. The finder-function returns a pointer to the
7986 ** sqlite_io_methods object that implements the desired locking
7987 ** behaviors. See the division above that contains the IOMETHODS
7988 ** macro for addition information on finder-functions.
7989 **
7990 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7991 ** object. But the "autolockIoFinder" available on MacOSX does a little
7992 ** more than that; it looks at the filesystem type that hosts the
7993 ** database file and tries to choose an locking method appropriate for
7994 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007995 */
drh7708e972008-11-29 00:56:52 +00007996 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007997 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007998 sizeof(unixFile), /* szOsFile */ \
7999 MAX_PATHNAME, /* mxPathname */ \
8000 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00008001 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00008002 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00008003 unixOpen, /* xOpen */ \
8004 unixDelete, /* xDelete */ \
8005 unixAccess, /* xAccess */ \
8006 unixFullPathname, /* xFullPathname */ \
8007 unixDlOpen, /* xDlOpen */ \
8008 unixDlError, /* xDlError */ \
8009 unixDlSym, /* xDlSym */ \
8010 unixDlClose, /* xDlClose */ \
8011 unixRandomness, /* xRandomness */ \
8012 unixSleep, /* xSleep */ \
8013 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00008014 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00008015 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00008016 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00008017 unixGetSystemCall, /* xGetSystemCall */ \
8018 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00008019 }
8020
drh6b9d6dd2008-12-03 19:34:47 +00008021 /*
8022 ** All default VFSes for unix are contained in the following array.
8023 **
8024 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
8025 ** by the SQLite core when the VFS is registered. So the following
8026 ** array cannot be const.
8027 */
danielk1977e339d652008-06-28 11:23:00 +00008028 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00008029#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00008030 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00008031#elif OS_VXWORKS
8032 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00008033#else
8034 UNIXVFS("unix", posixIoFinder ),
8035#endif
8036 UNIXVFS("unix-none", nolockIoFinder ),
8037 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00008038 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00008039#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00008040 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00008041#endif
drhe89b2912015-03-03 20:42:01 +00008042#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00008043 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00008044#endif
drhe89b2912015-03-03 20:42:01 +00008045#if SQLITE_ENABLE_LOCKING_STYLE
8046 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00008047#endif
drhd2cb50b2009-01-09 21:41:17 +00008048#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00008049 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00008050 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00008051 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00008052#endif
drh153c62c2007-08-24 03:51:33 +00008053 };
drh6b9d6dd2008-12-03 19:34:47 +00008054 unsigned int i; /* Loop counter */
8055
drh2aa5a002011-04-13 13:42:25 +00008056 /* Double-check that the aSyscall[] array has been constructed
8057 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00008058 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00008059
drh6b9d6dd2008-12-03 19:34:47 +00008060 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00008061 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh087f1432022-08-12 18:46:01 +00008062#ifdef SQLITE_DEFAULT_UNIX_VFS
8063 sqlite3_vfs_register(&aVfs[i],
8064 0==strcmp(aVfs[i].zName,SQLITE_DEFAULT_UNIX_VFS));
8065#else
drh734c9862008-11-28 15:37:20 +00008066 sqlite3_vfs_register(&aVfs[i], i==0);
drh087f1432022-08-12 18:46:01 +00008067#endif
danielk1977e339d652008-06-28 11:23:00 +00008068 }
drh20a9ed12022-09-17 18:29:49 +00008069#ifdef SQLITE_OS_KV_OPTIONAL
8070 sqlite3KvvfsInit();
8071#endif
drh56115892018-02-05 16:39:12 +00008072 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
drh187e2e42021-05-19 16:55:28 +00008073
drhf54e7942021-06-15 18:46:06 +00008074#ifndef SQLITE_OMIT_WAL
drh187e2e42021-05-19 16:55:28 +00008075 /* Validate lock assumptions */
8076 assert( SQLITE_SHM_NLOCK==8 ); /* Number of available locks */
8077 assert( UNIX_SHM_BASE==120 ); /* Start of locking area */
8078 /* Locks:
drh04f4b682021-05-19 19:27:42 +00008079 ** WRITE UNIX_SHM_BASE 120
8080 ** CKPT UNIX_SHM_BASE+1 121
8081 ** RECOVER UNIX_SHM_BASE+2 122
8082 ** READ-0 UNIX_SHM_BASE+3 123
8083 ** READ-1 UNIX_SHM_BASE+4 124
8084 ** READ-2 UNIX_SHM_BASE+5 125
8085 ** READ-3 UNIX_SHM_BASE+6 126
8086 ** READ-4 UNIX_SHM_BASE+7 127
8087 ** DMS UNIX_SHM_BASE+8 128
8088 */
drh187e2e42021-05-19 16:55:28 +00008089 assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */
drhf54e7942021-06-15 18:46:06 +00008090#endif
8091
dand9137e32021-11-19 14:02:43 +00008092 /* Initialize temp file dir array. */
8093 unixTempFileInit();
8094
danielk1977c0fa4c52008-06-25 17:19:00 +00008095 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00008096}
danielk1977e339d652008-06-28 11:23:00 +00008097
8098/*
drh6b9d6dd2008-12-03 19:34:47 +00008099** Shutdown the operating system interface.
8100**
8101** Some operating systems might need to do some cleanup in this routine,
8102** to release dynamically allocated objects. But not on unix.
8103** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00008104*/
danielk1977c0fa4c52008-06-25 17:19:00 +00008105int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00008106 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00008107 return SQLITE_OK;
8108}
drhdce8bdb2007-08-16 13:01:44 +00008109
danielk197729bafea2008-06-26 10:41:19 +00008110#endif /* SQLITE_OS_UNIX */