blob: 5419a042a63635c8145f58c71f9a3e9423a7d513 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drhe32a2562016-03-04 02:38:00 +000074/* Use pread() and pwrite() if they are available */
drh79a2ca32016-03-04 03:14:39 +000075#if defined(__APPLE__)
76# define HAVE_PREAD 1
77# define HAVE_PWRITE 1
78#endif
drhe32a2562016-03-04 02:38:00 +000079#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
80# undef USE_PREAD
drhe32a2562016-03-04 02:38:00 +000081# define USE_PREAD64 1
drhe32a2562016-03-04 02:38:00 +000082#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
drh79a2ca32016-03-04 03:14:39 +000083# undef USE_PREAD64
84# define USE_PREAD 1
drhe32a2562016-03-04 02:38:00 +000085#endif
86
drh9cbe6352005-11-29 03:13:21 +000087/*
drh9cbe6352005-11-29 03:13:21 +000088** standard include files.
89*/
90#include <sys/types.h>
91#include <sys/stat.h>
92#include <fcntl.h>
danefe16972017-07-20 19:49:14 +000093#include <sys/ioctl.h>
drh9cbe6352005-11-29 03:13:21 +000094#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000095#include <time.h>
drh19e2d372005-08-29 23:00:03 +000096#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000097#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000098#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000099# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000100#endif
drh1da88f02011-12-17 16:09:16 +0000101
drhe89b2912015-03-03 20:42:01 +0000102#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000103# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +0000104# include <sys/file.h>
105# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +0000106#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000107
drhe4079e12019-09-27 16:33:27 +0000108/*
109** Try to determine if gethostuuid() is available based on standard
110** macros. This might sometimes compute the wrong value for some
111** obscure platforms. For those cases, simply compile with one of
112** the following:
113**
114** -DHAVE_GETHOSTUUID=0
115** -DHAVE_GETHOSTUUID=1
116**
117** None if this matters except when building on Apple products with
118** -DSQLITE_ENABLE_LOCKING_STYLE.
119*/
120#ifndef HAVE_GETHOSTUUID
121# define HAVE_GETHOSTUUID 0
122# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
123 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
124# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
drh14f38b32020-08-19 23:51:54 +0000125 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\
126 && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0))
drhe4079e12019-09-27 16:33:27 +0000127# undef HAVE_GETHOSTUUID
128# define HAVE_GETHOSTUUID 1
129# else
130# warning "gethostuuid() is disabled."
131# endif
drh6bca6512015-04-13 23:05:28 +0000132# endif
133#endif
134
135
drhe89b2912015-03-03 20:42:01 +0000136#if OS_VXWORKS
137# include <sys/ioctl.h>
138# include <semaphore.h>
139# include <limits.h>
140#endif /* OS_VXWORKS */
141
142#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000143# include <sys/mount.h>
144#endif
145
drhdbe4b882011-06-20 18:00:17 +0000146#ifdef HAVE_UTIME
147# include <utime.h>
148#endif
149
drh9cbe6352005-11-29 03:13:21 +0000150/*
drh7ed97b92010-01-20 13:07:21 +0000151** Allowed values of unixFile.fsFlags
152*/
153#define SQLITE_FSFLAGS_IS_MSDOS 0x1
154
155/*
drh24efa542018-10-02 19:36:40 +0000156** If we are to be thread-safe, include the pthreads header.
drh9cbe6352005-11-29 03:13:21 +0000157*/
drhd677b3d2007-08-20 22:48:41 +0000158#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000159# include <pthread.h>
drh9cbe6352005-11-29 03:13:21 +0000160#endif
161
162/*
163** Default permissions when creating a new file
164*/
165#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
166# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
167#endif
168
danielk1977b4b47412007-08-17 15:53:36 +0000169/*
drh5adc60b2012-04-14 13:25:11 +0000170** Default permissions when creating auto proxy dir
171*/
aswiftaebf4132008-11-21 00:10:35 +0000172#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
173# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
174#endif
175
176/*
danielk1977b4b47412007-08-17 15:53:36 +0000177** Maximum supported path-length.
178*/
179#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000180
dane88ec182016-01-25 17:04:48 +0000181/*
182** Maximum supported symbolic links
183*/
184#define SQLITE_MAX_SYMLINKS 100
185
drh91eb93c2015-03-03 19:56:20 +0000186/* Always cast the getpid() return type for compatibility with
187** kernel modules in VxWorks. */
188#define osGetpid(X) (pid_t)getpid()
189
drh734c9862008-11-28 15:37:20 +0000190/*
drh734c9862008-11-28 15:37:20 +0000191** Only set the lastErrno if the error code is a real error and not
192** a normal expected return code of SQLITE_BUSY or SQLITE_OK
193*/
194#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
195
drhd91c68f2010-05-14 14:52:25 +0000196/* Forward references */
197typedef struct unixShm unixShm; /* Connection shared memory */
198typedef struct unixShmNode unixShmNode; /* Shared memory instance */
199typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
200typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000201
202/*
dane946c392009-08-22 11:39:46 +0000203** Sometimes, after a file handle is closed by SQLite, the file descriptor
204** cannot be closed immediately. In these cases, instances of the following
205** structure are used to store the file descriptor while waiting for an
206** opportunity to either close or reuse it.
207*/
dane946c392009-08-22 11:39:46 +0000208struct UnixUnusedFd {
209 int fd; /* File descriptor to close */
210 int flags; /* Flags this file descriptor was opened with */
211 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
212};
213
214/*
drh9b35ea62008-11-29 02:20:26 +0000215** The unixFile structure is subclass of sqlite3_file specific to the unix
216** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000217*/
drh054889e2005-11-30 03:20:31 +0000218typedef struct unixFile unixFile;
219struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000220 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000221 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000222 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000223 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000224 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000225 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000226 int lastErrno; /* The unix errno from last I/O error */
227 void *lockingContext; /* Locking style specific state */
drhc68886b2017-08-18 16:09:52 +0000228 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000229 const char *zPath; /* Name of the file */
230 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000231 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000232#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000233 int nFetchOut; /* Number of outstanding xFetch refs */
234 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000235 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
236 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000237 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000238#endif
drh537dddf2012-10-26 13:46:24 +0000239 int sectorSize; /* Device sector size */
240 int deviceCharacteristics; /* Precomputed device characteristics */
drh08c6d442009-02-09 17:34:07 +0000241#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000242 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000243#endif
drh7ed97b92010-01-20 13:07:21 +0000244#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000245 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000246#endif
drhf0119b22018-03-26 17:40:53 +0000247#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
248 unsigned iBusyTimeout; /* Wait this many millisec on locks */
249#endif
drh6c7d5c52008-11-21 20:32:33 +0000250#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000251 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000252#endif
drhd3d8c042012-05-29 17:02:40 +0000253#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000254 /* The next group of variables are used to track whether or not the
255 ** transaction counter in bytes 24-27 of database files are updated
256 ** whenever any part of the database changes. An assertion fault will
257 ** occur if a file is updated without also updating the transaction
258 ** counter. This test is made to avoid new problems similar to the
259 ** one described by ticket #3584.
260 */
261 unsigned char transCntrChng; /* True if the transaction counter changed */
262 unsigned char dbUpdate; /* True if any part of database file changed */
263 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000264
drh8f941bc2009-01-14 23:03:40 +0000265#endif
danf23da962013-03-23 21:00:41 +0000266
danielk1977967a4a12007-08-20 14:23:44 +0000267#ifdef SQLITE_TEST
268 /* In test mode, increase the size of this structure a bit so that
269 ** it is larger than the struct CrashFile defined in test6.c.
270 */
271 char aPadding[32];
272#endif
drh9cbe6352005-11-29 03:13:21 +0000273};
274
drhb00d8622014-01-01 15:18:36 +0000275/* This variable holds the process id (pid) from when the xRandomness()
276** method was called. If xOpen() is called from a different process id,
277** indicating that a fork() has occurred, the PRNG will be reset.
278*/
drh8cd5b252015-03-02 22:06:43 +0000279static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000280
drh0ccebe72005-06-07 22:22:50 +0000281/*
drha7e61d82011-03-12 17:02:57 +0000282** Allowed values for the unixFile.ctrlFlags bitmask:
283*/
drhf0b190d2011-07-26 16:03:07 +0000284#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
285#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
286#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000287#ifndef SQLITE_DISABLE_DIRSYNC
288# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
289#else
290# define UNIXFILE_DIRSYNC 0x00
291#endif
drhcb15f352011-12-23 01:04:17 +0000292#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000293#define UNIXFILE_DELETE 0x20 /* Delete on close */
294#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
295#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000296
297/*
drh198bf392006-01-06 21:52:49 +0000298** Include code that is common to all os_*.c files
299*/
300#include "os_common.h"
301
302/*
drh0ccebe72005-06-07 22:22:50 +0000303** Define various macros that are missing from some systems.
304*/
drhbbd42a62004-05-22 17:41:58 +0000305#ifndef O_LARGEFILE
306# define O_LARGEFILE 0
307#endif
308#ifdef SQLITE_DISABLE_LFS
309# undef O_LARGEFILE
310# define O_LARGEFILE 0
311#endif
312#ifndef O_NOFOLLOW
313# define O_NOFOLLOW 0
314#endif
315#ifndef O_BINARY
316# define O_BINARY 0
317#endif
318
319/*
drh2b4b5962005-06-15 17:47:55 +0000320** The threadid macro resolves to the thread-id or to 0. Used for
321** testing and debugging only.
322*/
drhd677b3d2007-08-20 22:48:41 +0000323#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000324#define threadid pthread_self()
325#else
326#define threadid 0
327#endif
328
drh99ab3b12011-03-02 15:09:07 +0000329/*
dane6ecd662013-04-01 17:56:59 +0000330** HAVE_MREMAP defaults to true on Linux and false everywhere else.
331*/
332#if !defined(HAVE_MREMAP)
333# if defined(__linux__) && defined(_GNU_SOURCE)
334# define HAVE_MREMAP 1
335# else
336# define HAVE_MREMAP 0
337# endif
338#endif
339
340/*
dan2ee53412014-09-06 16:49:40 +0000341** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
342** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
343*/
344#ifdef __ANDROID__
345# define lseek lseek64
346#endif
347
drhd76dba72017-07-22 16:00:34 +0000348#ifdef __linux__
349/*
350** Linux-specific IOCTL magic numbers used for controlling F2FS
351*/
danefe16972017-07-20 19:49:14 +0000352#define F2FS_IOCTL_MAGIC 0xf5
353#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
354#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
355#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
356#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
dan9d709542017-07-21 21:06:24 +0000357#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
dan9d709542017-07-21 21:06:24 +0000358#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
drhd76dba72017-07-22 16:00:34 +0000359#endif /* __linux__ */
danefe16972017-07-20 19:49:14 +0000360
361
dan2ee53412014-09-06 16:49:40 +0000362/*
drh9a3baf12011-04-25 18:01:27 +0000363** Different Unix systems declare open() in different ways. Same use
364** open(const char*,int,mode_t). Others use open(const char*,int,...).
365** The difference is important when using a pointer to the function.
366**
367** The safest way to deal with the problem is to always use this wrapper
368** which always has the same well-defined interface.
369*/
370static int posixOpen(const char *zFile, int flags, int mode){
371 return open(zFile, flags, mode);
372}
373
drh90315a22011-08-10 01:52:12 +0000374/* Forward reference */
375static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000376static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000377
drh9a3baf12011-04-25 18:01:27 +0000378/*
drh99ab3b12011-03-02 15:09:07 +0000379** Many system calls are accessed through pointer-to-functions so that
380** they may be overridden at runtime to facilitate fault injection during
381** testing and sandboxing. The following array holds the names and pointers
382** to all overrideable system calls.
383*/
384static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000385 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000386 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
387 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000388} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000389 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
390#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000391
drh58ad5802011-03-23 22:02:23 +0000392 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000393#define osClose ((int(*)(int))aSyscall[1].pCurrent)
394
drh58ad5802011-03-23 22:02:23 +0000395 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000396#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
397
drh58ad5802011-03-23 22:02:23 +0000398 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000399#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
400
drh58ad5802011-03-23 22:02:23 +0000401 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000402#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
403
404/*
405** The DJGPP compiler environment looks mostly like Unix, but it
406** lacks the fcntl() system call. So redefine fcntl() to be something
407** that always succeeds. This means that locking does not occur under
408** DJGPP. But it is DOS - what did you expect?
409*/
410#ifdef __DJGPP__
411 { "fstat", 0, 0 },
412#define osFstat(a,b,c) 0
413#else
drh58ad5802011-03-23 22:02:23 +0000414 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000415#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
416#endif
417
drh58ad5802011-03-23 22:02:23 +0000418 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000419#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
420
drh58ad5802011-03-23 22:02:23 +0000421 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000422#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000423
drh58ad5802011-03-23 22:02:23 +0000424 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000425#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
426
drhe89b2912015-03-03 20:42:01 +0000427#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000428 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000429#else
drh58ad5802011-03-23 22:02:23 +0000430 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000431#endif
432#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
433
434#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000435 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000436#else
drh58ad5802011-03-23 22:02:23 +0000437 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000438#endif
drhf9986d92016-04-18 13:09:55 +0000439#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
drhe562be52011-03-02 18:01:10 +0000440
drh58ad5802011-03-23 22:02:23 +0000441 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000442#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
443
drhe89b2912015-03-03 20:42:01 +0000444#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000445 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000446#else
drh58ad5802011-03-23 22:02:23 +0000447 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000448#endif
449#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
450 aSyscall[12].pCurrent)
451
452#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000453 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000454#else
drh58ad5802011-03-23 22:02:23 +0000455 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000456#endif
drhf9986d92016-04-18 13:09:55 +0000457#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
drhe562be52011-03-02 18:01:10 +0000458 aSyscall[13].pCurrent)
459
drh6226ca22015-11-24 15:06:28 +0000460 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000461#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000462
463#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000464 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000465#else
drh58ad5802011-03-23 22:02:23 +0000466 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000467#endif
dan0fd7d862011-03-29 10:04:23 +0000468#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000469
drh036ac7f2011-08-08 23:18:05 +0000470 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
471#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
472
drh90315a22011-08-10 01:52:12 +0000473 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
474#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
475
drh9ef6bc42011-11-04 02:24:02 +0000476 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
477#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
478
479 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
480#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
481
drhe2258a22016-01-12 00:37:55 +0000482#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000483 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000484#else
485 { "fchown", (sqlite3_syscall_ptr)0, 0 },
486#endif
dand3eaebd2012-02-13 08:50:23 +0000487#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000488
drh26f625f2018-02-19 16:34:31 +0000489#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000490 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
drh26f625f2018-02-19 16:34:31 +0000491#else
492 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
493#endif
drh6226ca22015-11-24 15:06:28 +0000494#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
495
dan4dd51442013-08-26 14:30:25 +0000496#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000497 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
498#else
499 { "mmap", (sqlite3_syscall_ptr)0, 0 },
500#endif
drh6226ca22015-11-24 15:06:28 +0000501#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000502
drhe4a08f92016-01-08 19:17:30 +0000503#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000504 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000505#else
drha8299922016-01-08 22:31:00 +0000506 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000507#endif
drh62be1fa2017-12-09 01:02:33 +0000508#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000509
drhe4a08f92016-01-08 19:17:30 +0000510#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000511 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
512#else
513 { "mremap", (sqlite3_syscall_ptr)0, 0 },
514#endif
drh6226ca22015-11-24 15:06:28 +0000515#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
516
drh24dbeae2016-01-08 22:18:00 +0000517#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000518 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000519#else
520 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
521#endif
drh6226ca22015-11-24 15:06:28 +0000522#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000523
drhe2258a22016-01-12 00:37:55 +0000524#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000525 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000526#else
527 { "readlink", (sqlite3_syscall_ptr)0, 0 },
528#endif
drh6226ca22015-11-24 15:06:28 +0000529#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000530
danaf1b36b2016-01-25 18:43:05 +0000531#if defined(HAVE_LSTAT)
532 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
533#else
534 { "lstat", (sqlite3_syscall_ptr)0, 0 },
535#endif
dancaf6b152016-01-25 18:05:49 +0000536#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000537
drhb5d013e2017-10-25 16:14:12 +0000538#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
dan16f39b62018-09-18 19:40:18 +0000539# ifdef __ANDROID__
540 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
danec9b2a12019-07-15 07:58:28 +0000541#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
dan16f39b62018-09-18 19:40:18 +0000542# else
danefe16972017-07-20 19:49:14 +0000543 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
danec9b2a12019-07-15 07:58:28 +0000544#define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
dan16f39b62018-09-18 19:40:18 +0000545# endif
drhb5d013e2017-10-25 16:14:12 +0000546#else
547 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
548#endif
danefe16972017-07-20 19:49:14 +0000549
drhe562be52011-03-02 18:01:10 +0000550}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000551
drh6226ca22015-11-24 15:06:28 +0000552
553/*
554** On some systems, calls to fchown() will trigger a message in a security
555** log if they come from non-root processes. So avoid calling fchown() if
556** we are not running as root.
557*/
558static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000559#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000560 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000561#else
562 return 0;
drh6226ca22015-11-24 15:06:28 +0000563#endif
564}
565
drh99ab3b12011-03-02 15:09:07 +0000566/*
567** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000568** "unix" VFSes. Return SQLITE_OK opon successfully updating the
569** system call pointer, or SQLITE_NOTFOUND if there is no configurable
570** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000571*/
572static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000573 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
574 const char *zName, /* Name of system call to override */
575 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000576){
drh58ad5802011-03-23 22:02:23 +0000577 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000578 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000579
580 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000581 if( zName==0 ){
582 /* If no zName is given, restore all system calls to their default
583 ** settings and return NULL
584 */
dan51438a72011-04-02 17:00:47 +0000585 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000586 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
587 if( aSyscall[i].pDefault ){
588 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000589 }
590 }
591 }else{
592 /* If zName is specified, operate on only the one system call
593 ** specified.
594 */
595 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
596 if( strcmp(zName, aSyscall[i].zName)==0 ){
597 if( aSyscall[i].pDefault==0 ){
598 aSyscall[i].pDefault = aSyscall[i].pCurrent;
599 }
drh1df30962011-03-02 19:06:42 +0000600 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000601 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
602 aSyscall[i].pCurrent = pNewFunc;
603 break;
604 }
605 }
606 }
607 return rc;
608}
609
drh1df30962011-03-02 19:06:42 +0000610/*
611** Return the value of a system call. Return NULL if zName is not a
612** recognized system call name. NULL is also returned if the system call
613** is currently undefined.
614*/
drh58ad5802011-03-23 22:02:23 +0000615static sqlite3_syscall_ptr unixGetSystemCall(
616 sqlite3_vfs *pNotUsed,
617 const char *zName
618){
619 unsigned int i;
620
621 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000622 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
623 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
624 }
625 return 0;
626}
627
628/*
629** Return the name of the first system call after zName. If zName==NULL
630** then return the name of the first system call. Return NULL if zName
631** is the last system call or if zName is not the name of a valid
632** system call.
633*/
634static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000635 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000636
637 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000638 if( zName ){
639 for(i=0; i<ArraySize(aSyscall)-1; i++){
640 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000641 }
642 }
dan0fd7d862011-03-29 10:04:23 +0000643 for(i++; i<ArraySize(aSyscall); i++){
644 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000645 }
646 return 0;
647}
648
drhad4f1e52011-03-04 15:43:57 +0000649/*
drh77a3fdc2013-08-30 14:24:12 +0000650** Do not accept any file descriptor less than this value, in order to avoid
651** opening database file using file descriptors that are commonly used for
652** standard input, output, and error.
653*/
654#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
655# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
656#endif
657
658/*
drh8c815d12012-02-13 20:16:37 +0000659** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000660** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000661**
662** If the file creation mode "m" is 0 then set it to the default for
663** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
664** 0644) as modified by the system umask. If m is not 0, then
665** make the file creation mode be exactly m ignoring the umask.
666**
667** The m parameter will be non-zero only when creating -wal, -journal,
668** and -shm files. We want those files to have *exactly* the same
669** permissions as their original database, unadulterated by the umask.
670** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
671** transaction crashes and leaves behind hot journals, then any
672** process that is able to write to the database will also be able to
673** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000674*/
drh8c815d12012-02-13 20:16:37 +0000675static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000676 int fd;
drhe1186ab2013-01-04 20:45:13 +0000677 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000678 while(1){
drh5adc60b2012-04-14 13:25:11 +0000679#if defined(O_CLOEXEC)
680 fd = osOpen(z,f|O_CLOEXEC,m2);
681#else
682 fd = osOpen(z,f,m2);
683#endif
drh5128d002013-08-30 06:20:23 +0000684 if( fd<0 ){
685 if( errno==EINTR ) continue;
686 break;
687 }
drh77a3fdc2013-08-30 14:24:12 +0000688 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000689 osClose(fd);
690 sqlite3_log(SQLITE_WARNING,
691 "attempt to open \"%s\" as file descriptor %d", z, fd);
692 fd = -1;
drh0ba36212020-02-13 13:45:04 +0000693 if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
drh5128d002013-08-30 06:20:23 +0000694 }
drhe1186ab2013-01-04 20:45:13 +0000695 if( fd>=0 ){
696 if( m!=0 ){
697 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000698 if( osFstat(fd, &statbuf)==0
699 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000700 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000701 ){
drhe1186ab2013-01-04 20:45:13 +0000702 osFchmod(fd, m);
703 }
704 }
drh5adc60b2012-04-14 13:25:11 +0000705#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000706 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000707#endif
drhe1186ab2013-01-04 20:45:13 +0000708 }
drh5adc60b2012-04-14 13:25:11 +0000709 return fd;
drhad4f1e52011-03-04 15:43:57 +0000710}
danielk197713adf8a2004-06-03 16:08:41 +0000711
drh107886a2008-11-21 22:21:50 +0000712/*
dan9359c7b2009-08-21 08:29:10 +0000713** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000714** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000715** vxworksFileId objects used by this file, all of which may be
716** shared by multiple threads.
717**
718** Function unixMutexHeld() is used to assert() that the global mutex
719** is held when required. This function is only used as part of assert()
720** statements. e.g.
721**
722** unixEnterMutex()
723** assert( unixMutexHeld() );
724** unixEnterLeave()
drh095908e2018-08-13 20:46:18 +0000725**
726** To prevent deadlock, the global unixBigLock must must be acquired
727** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
728** OK to get the pLockMutex without holding unixBigLock first, but if
729** that happens, the unixBigLock mutex must not be acquired until after
730** pLockMutex is released.
731**
732** OK: enter(unixBigLock), enter(pLockInfo)
733** OK: enter(unixBigLock)
734** OK: enter(pLockInfo)
735** ERROR: enter(pLockInfo), enter(unixBigLock)
drh107886a2008-11-21 22:21:50 +0000736*/
drh56115892018-02-05 16:39:12 +0000737static sqlite3_mutex *unixBigLock = 0;
drh107886a2008-11-21 22:21:50 +0000738static void unixEnterMutex(void){
drh095908e2018-08-13 20:46:18 +0000739 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
drh56115892018-02-05 16:39:12 +0000740 sqlite3_mutex_enter(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000741}
742static void unixLeaveMutex(void){
drh095908e2018-08-13 20:46:18 +0000743 assert( sqlite3_mutex_held(unixBigLock) );
drh56115892018-02-05 16:39:12 +0000744 sqlite3_mutex_leave(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000745}
dan9359c7b2009-08-21 08:29:10 +0000746#ifdef SQLITE_DEBUG
747static int unixMutexHeld(void) {
drh56115892018-02-05 16:39:12 +0000748 return sqlite3_mutex_held(unixBigLock);
dan9359c7b2009-08-21 08:29:10 +0000749}
750#endif
drh107886a2008-11-21 22:21:50 +0000751
drh734c9862008-11-28 15:37:20 +0000752
mistachkinfb383e92015-04-16 03:24:38 +0000753#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000754/*
755** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000756** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000757** integer lock-type.
758*/
drh308c2a52010-05-14 11:30:18 +0000759static const char *azFileLock(int eFileLock){
760 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000761 case NO_LOCK: return "NONE";
762 case SHARED_LOCK: return "SHARED";
763 case RESERVED_LOCK: return "RESERVED";
764 case PENDING_LOCK: return "PENDING";
765 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000766 }
767 return "ERROR";
768}
769#endif
770
771#ifdef SQLITE_LOCK_TRACE
772/*
773** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000774**
drh734c9862008-11-28 15:37:20 +0000775** This routine is used for troubleshooting locks on multithreaded
776** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
777** command-line option on the compiler. This code is normally
778** turned off.
779*/
780static int lockTrace(int fd, int op, struct flock *p){
781 char *zOpName, *zType;
782 int s;
783 int savedErrno;
784 if( op==F_GETLK ){
785 zOpName = "GETLK";
786 }else if( op==F_SETLK ){
787 zOpName = "SETLK";
788 }else{
drh99ab3b12011-03-02 15:09:07 +0000789 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000790 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
791 return s;
792 }
793 if( p->l_type==F_RDLCK ){
794 zType = "RDLCK";
795 }else if( p->l_type==F_WRLCK ){
796 zType = "WRLCK";
797 }else if( p->l_type==F_UNLCK ){
798 zType = "UNLCK";
799 }else{
800 assert( 0 );
801 }
802 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000803 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000804 savedErrno = errno;
805 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
806 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
807 (int)p->l_pid, s);
808 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
809 struct flock l2;
810 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000811 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000812 if( l2.l_type==F_RDLCK ){
813 zType = "RDLCK";
814 }else if( l2.l_type==F_WRLCK ){
815 zType = "WRLCK";
816 }else if( l2.l_type==F_UNLCK ){
817 zType = "UNLCK";
818 }else{
819 assert( 0 );
820 }
821 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
822 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
823 }
824 errno = savedErrno;
825 return s;
826}
drh99ab3b12011-03-02 15:09:07 +0000827#undef osFcntl
828#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000829#endif /* SQLITE_LOCK_TRACE */
830
drhff812312011-02-23 13:33:46 +0000831/*
832** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000833**
drhe6d41732015-02-21 00:49:00 +0000834** All calls to ftruncate() within this file should be made through
835** this wrapper. On the Android platform, bypassing the logic below
836** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000837*/
drhff812312011-02-23 13:33:46 +0000838static int robust_ftruncate(int h, sqlite3_int64 sz){
839 int rc;
dan2ee53412014-09-06 16:49:40 +0000840#ifdef __ANDROID__
841 /* On Android, ftruncate() always uses 32-bit offsets, even if
842 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000843 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000844 ** such attempts. */
845 if( sz>(sqlite3_int64)0x7FFFFFFF ){
846 rc = SQLITE_OK;
847 }else
848#endif
drh99ab3b12011-03-02 15:09:07 +0000849 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000850 return rc;
851}
drh734c9862008-11-28 15:37:20 +0000852
853/*
854** This routine translates a standard POSIX errno code into something
855** useful to the clients of the sqlite3 functions. Specifically, it is
856** intended to translate a variety of "try again" errors into SQLITE_BUSY
857** and a variety of "please close the file descriptor NOW" errors into
858** SQLITE_IOERR
859**
860** Errors during initialization of locks, or file system support for locks,
861** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
862*/
863static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000864 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
865 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
866 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
867 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000868 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000869 case EACCES:
drh734c9862008-11-28 15:37:20 +0000870 case EAGAIN:
871 case ETIMEDOUT:
872 case EBUSY:
873 case EINTR:
874 case ENOLCK:
875 /* random NFS retry error, unless during file system support
876 * introspection, in which it actually means what it says */
877 return SQLITE_BUSY;
878
drh734c9862008-11-28 15:37:20 +0000879 case EPERM:
880 return SQLITE_PERM;
881
drh734c9862008-11-28 15:37:20 +0000882 default:
883 return sqliteIOErr;
884 }
885}
886
887
drh734c9862008-11-28 15:37:20 +0000888/******************************************************************************
889****************** Begin Unique File ID Utility Used By VxWorks ***************
890**
891** On most versions of unix, we can get a unique ID for a file by concatenating
892** the device number and the inode number. But this does not work on VxWorks.
893** On VxWorks, a unique file id must be based on the canonical filename.
894**
895** A pointer to an instance of the following structure can be used as a
896** unique file ID in VxWorks. Each instance of this structure contains
897** a copy of the canonical filename. There is also a reference count.
898** The structure is reclaimed when the number of pointers to it drops to
899** zero.
900**
901** There are never very many files open at one time and lookups are not
902** a performance-critical path, so it is sufficient to put these
903** structures on a linked list.
904*/
905struct vxworksFileId {
906 struct vxworksFileId *pNext; /* Next in a list of them all */
907 int nRef; /* Number of references to this one */
908 int nName; /* Length of the zCanonicalName[] string */
909 char *zCanonicalName; /* Canonical filename */
910};
911
912#if OS_VXWORKS
913/*
drh9b35ea62008-11-29 02:20:26 +0000914** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000915** variable:
916*/
917static struct vxworksFileId *vxworksFileList = 0;
918
919/*
920** Simplify a filename into its canonical form
921** by making the following changes:
922**
923** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000924** * convert /./ into just /
925** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000926**
927** Changes are made in-place. Return the new name length.
928**
929** The original filename is in z[0..n-1]. Return the number of
930** characters in the simplified name.
931*/
932static int vxworksSimplifyName(char *z, int n){
933 int i, j;
934 while( n>1 && z[n-1]=='/' ){ n--; }
935 for(i=j=0; i<n; i++){
936 if( z[i]=='/' ){
937 if( z[i+1]=='/' ) continue;
938 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
939 i += 1;
940 continue;
941 }
942 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
943 while( j>0 && z[j-1]!='/' ){ j--; }
944 if( j>0 ){ j--; }
945 i += 2;
946 continue;
947 }
948 }
949 z[j++] = z[i];
950 }
951 z[j] = 0;
952 return j;
953}
954
955/*
956** Find a unique file ID for the given absolute pathname. Return
957** a pointer to the vxworksFileId object. This pointer is the unique
958** file ID.
959**
960** The nRef field of the vxworksFileId object is incremented before
961** the object is returned. A new vxworksFileId object is created
962** and added to the global list if necessary.
963**
964** If a memory allocation error occurs, return NULL.
965*/
966static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
967 struct vxworksFileId *pNew; /* search key and new file ID */
968 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
969 int n; /* Length of zAbsoluteName string */
970
971 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000972 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000973 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000974 if( pNew==0 ) return 0;
975 pNew->zCanonicalName = (char*)&pNew[1];
976 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
977 n = vxworksSimplifyName(pNew->zCanonicalName, n);
978
979 /* Search for an existing entry that matching the canonical name.
980 ** If found, increment the reference count and return a pointer to
981 ** the existing file ID.
982 */
983 unixEnterMutex();
984 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
985 if( pCandidate->nName==n
986 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
987 ){
988 sqlite3_free(pNew);
989 pCandidate->nRef++;
990 unixLeaveMutex();
991 return pCandidate;
992 }
993 }
994
995 /* No match was found. We will make a new file ID */
996 pNew->nRef = 1;
997 pNew->nName = n;
998 pNew->pNext = vxworksFileList;
999 vxworksFileList = pNew;
1000 unixLeaveMutex();
1001 return pNew;
1002}
1003
1004/*
1005** Decrement the reference count on a vxworksFileId object. Free
1006** the object when the reference count reaches zero.
1007*/
1008static void vxworksReleaseFileId(struct vxworksFileId *pId){
1009 unixEnterMutex();
1010 assert( pId->nRef>0 );
1011 pId->nRef--;
1012 if( pId->nRef==0 ){
1013 struct vxworksFileId **pp;
1014 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
1015 assert( *pp==pId );
1016 *pp = pId->pNext;
1017 sqlite3_free(pId);
1018 }
1019 unixLeaveMutex();
1020}
1021#endif /* OS_VXWORKS */
1022/*************** End of Unique File ID Utility Used By VxWorks ****************
1023******************************************************************************/
1024
1025
1026/******************************************************************************
1027*************************** Posix Advisory Locking ****************************
1028**
drh9b35ea62008-11-29 02:20:26 +00001029** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +00001030** section 6.5.2.2 lines 483 through 490 specify that when a process
1031** sets or clears a lock, that operation overrides any prior locks set
1032** by the same process. It does not explicitly say so, but this implies
1033** that it overrides locks set by the same process using a different
1034** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +00001035**
1036** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +00001037** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1038**
1039** Suppose ./file1 and ./file2 are really the same file (because
1040** one is a hard or symbolic link to the other) then if you set
1041** an exclusive lock on fd1, then try to get an exclusive lock
1042** on fd2, it works. I would have expected the second lock to
1043** fail since there was already a lock on the file due to fd1.
1044** But not so. Since both locks came from the same process, the
1045** second overrides the first, even though they were on different
1046** file descriptors opened on different file names.
1047**
drh734c9862008-11-28 15:37:20 +00001048** This means that we cannot use POSIX locks to synchronize file access
1049** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001050** to synchronize access for threads in separate processes, but not
1051** threads within the same process.
1052**
1053** To work around the problem, SQLite has to manage file locks internally
1054** on its own. Whenever a new database is opened, we have to find the
1055** specific inode of the database file (the inode is determined by the
1056** st_dev and st_ino fields of the stat structure that fstat() fills in)
1057** and check for locks already existing on that inode. When locks are
1058** created or removed, we have to look at our own internal record of the
1059** locks to see if another thread has previously set a lock on that same
1060** inode.
1061**
drh9b35ea62008-11-29 02:20:26 +00001062** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1063** For VxWorks, we have to use the alternative unique ID system based on
1064** canonical filename and implemented in the previous division.)
1065**
danielk1977ad94b582007-08-20 06:44:22 +00001066** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001067** descriptor. It is now a structure that holds the integer file
1068** descriptor and a pointer to a structure that describes the internal
1069** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001070** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001071** point to the same locking structure. The locking structure keeps
1072** a reference count (so we will know when to delete it) and a "cnt"
1073** field that tells us its internal lock status. cnt==0 means the
1074** file is unlocked. cnt==-1 means the file has an exclusive lock.
1075** cnt>0 means there are cnt shared locks on the file.
1076**
1077** Any attempt to lock or unlock a file first checks the locking
1078** structure. The fcntl() system call is only invoked to set a
1079** POSIX lock if the internal lock structure transitions between
1080** a locked and an unlocked state.
1081**
drh734c9862008-11-28 15:37:20 +00001082** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001083**
1084** If you close a file descriptor that points to a file that has locks,
1085** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001086** released. To work around this problem, each unixInodeInfo object
1087** maintains a count of the number of pending locks on tha inode.
1088** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001089** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001090** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001091** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001092** be closed and that list is walked (and cleared) when the last lock
1093** clears.
1094**
drh9b35ea62008-11-29 02:20:26 +00001095** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001096**
drh9b35ea62008-11-29 02:20:26 +00001097** Many older versions of linux use the LinuxThreads library which is
1098** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001099** A cannot be modified or overridden by a different thread B.
1100** Only thread A can modify the lock. Locking behavior is correct
1101** if the appliation uses the newer Native Posix Thread Library (NPTL)
1102** on linux - with NPTL a lock created by thread A can override locks
1103** in thread B. But there is no way to know at compile-time which
1104** threading library is being used. So there is no way to know at
1105** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001106** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001107** current process.
drh5fdae772004-06-29 03:29:00 +00001108**
drh8af6c222010-05-14 12:43:01 +00001109** SQLite used to support LinuxThreads. But support for LinuxThreads
1110** was dropped beginning with version 3.7.0. SQLite will still work with
1111** LinuxThreads provided that (1) there is no more than one connection
1112** per database file in the same process and (2) database connections
1113** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001114*/
1115
1116/*
1117** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001118** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001119*/
1120struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001121 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001122#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001123 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001124#else
drh25ef7f52016-12-05 20:06:45 +00001125 /* We are told that some versions of Android contain a bug that
1126 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1127 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1128 ** To work around this, always allocate 64-bits for the inode number.
1129 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1130 ** but that should not be a big deal. */
1131 /* WAS: ino_t ino; */
1132 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001133#endif
1134};
1135
1136/*
drhbbd42a62004-05-22 17:41:58 +00001137** An instance of the following structure is allocated for each open
drh24efa542018-10-02 19:36:40 +00001138** inode.
drhbbd42a62004-05-22 17:41:58 +00001139**
danielk1977ad94b582007-08-20 06:44:22 +00001140** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001141** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001142** object keeps a count of the number of unixFile pointing to it.
drhda6dc242018-07-23 21:10:37 +00001143**
1144** Mutex rules:
1145**
drh095908e2018-08-13 20:46:18 +00001146** (1) Only the pLockMutex mutex must be held in order to read or write
drhda6dc242018-07-23 21:10:37 +00001147** any of the locking fields:
drhef52b362018-08-13 22:50:34 +00001148** nShared, nLock, eFileLock, bProcessLock, pUnused
drhda6dc242018-07-23 21:10:37 +00001149**
1150** (2) When nRef>0, then the following fields are unchanging and can
1151** be read (but not written) without holding any mutex:
1152** fileId, pLockMutex
1153**
drhef52b362018-08-13 22:50:34 +00001154** (3) With the exceptions above, all the fields may only be read
drhda6dc242018-07-23 21:10:37 +00001155** or written while holding the global unixBigLock mutex.
drh095908e2018-08-13 20:46:18 +00001156**
1157** Deadlock prevention: The global unixBigLock mutex may not
1158** be acquired while holding the pLockMutex mutex. If both unixBigLock
1159** and pLockMutex are needed, then unixBigLock must be acquired first.
drhbbd42a62004-05-22 17:41:58 +00001160*/
drh8af6c222010-05-14 12:43:01 +00001161struct unixInodeInfo {
1162 struct unixFileId fileId; /* The lookup key */
drhda6dc242018-07-23 21:10:37 +00001163 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1164 int nShared; /* Number of SHARED locks held */
1165 int nLock; /* Number of outstanding file locks */
1166 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1167 unsigned char bProcessLock; /* An exclusive process lock is held */
drhef52b362018-08-13 22:50:34 +00001168 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh734c9862008-11-28 15:37:20 +00001169 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001170 unixShmNode *pShmNode; /* Shared memory associated with this inode */
drhd91c68f2010-05-14 14:52:25 +00001171 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1172 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001173#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001174 unsigned long long sharedByte; /* for AFP simulated shared lock */
1175#endif
drh6c7d5c52008-11-21 20:32:33 +00001176#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001177 sem_t *pSem; /* Named POSIX semaphore */
1178 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001179#endif
drhbbd42a62004-05-22 17:41:58 +00001180};
1181
drhda0e7682008-07-30 15:27:54 +00001182/*
drh8af6c222010-05-14 12:43:01 +00001183** A lists of all unixInodeInfo objects.
drh24efa542018-10-02 19:36:40 +00001184**
1185** Must hold unixBigLock in order to read or write this variable.
drhbbd42a62004-05-22 17:41:58 +00001186*/
drhc68886b2017-08-18 16:09:52 +00001187static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
drh095908e2018-08-13 20:46:18 +00001188
1189#ifdef SQLITE_DEBUG
1190/*
drh24efa542018-10-02 19:36:40 +00001191** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
1192** This routine is used only within assert() to help verify correct mutex
1193** usage.
drh095908e2018-08-13 20:46:18 +00001194*/
1195int unixFileMutexHeld(unixFile *pFile){
1196 assert( pFile->pInode );
1197 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1198}
1199int unixFileMutexNotheld(unixFile *pFile){
1200 assert( pFile->pInode );
1201 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1202}
1203#endif
drh5fdae772004-06-29 03:29:00 +00001204
drh5fdae772004-06-29 03:29:00 +00001205/*
dane18d4952011-02-21 11:46:24 +00001206**
drhaaeaa182015-11-24 15:12:47 +00001207** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001208** unixLogError().
1209**
1210** It is invoked after an error occurs in an OS function and errno has been
1211** set. It logs a message using sqlite3_log() containing the current value of
1212** errno and, if possible, the human-readable equivalent from strerror() or
1213** strerror_r().
1214**
1215** The first argument passed to the macro should be the error code that
1216** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1217** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001218** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001219** if any.
1220*/
drh0e9365c2011-03-02 02:08:13 +00001221#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1222static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001223 int errcode, /* SQLite error code */
1224 const char *zFunc, /* Name of OS function that failed */
1225 const char *zPath, /* File path associated with error */
1226 int iLine /* Source line number where error occurred */
1227){
1228 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001229 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001230
1231 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1232 ** the strerror() function to obtain the human-readable error message
1233 ** equivalent to errno. Otherwise, use strerror_r().
1234 */
1235#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1236 char aErr[80];
1237 memset(aErr, 0, sizeof(aErr));
1238 zErr = aErr;
1239
1240 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001241 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001242 ** returns a pointer to a buffer containing the error message. That pointer
1243 ** may point to aErr[], or it may point to some static storage somewhere.
1244 ** Otherwise, assume that the system provides the POSIX version of
1245 ** strerror_r(), which always writes an error message into aErr[].
1246 **
1247 ** If the code incorrectly assumes that it is the POSIX version that is
1248 ** available, the error message will often be an empty string. Not a
1249 ** huge problem. Incorrectly concluding that the GNU version is available
1250 ** could lead to a segfault though.
1251 */
1252#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1253 zErr =
1254# endif
drh0e9365c2011-03-02 02:08:13 +00001255 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001256
1257#elif SQLITE_THREADSAFE
1258 /* This is a threadsafe build, but strerror_r() is not available. */
1259 zErr = "";
1260#else
1261 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001262 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001263#endif
1264
drh0e9365c2011-03-02 02:08:13 +00001265 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001266 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001267 "os_unix.c:%d: (%d) %s(%s) - %s",
1268 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001269 );
1270
1271 return errcode;
1272}
1273
drh0e9365c2011-03-02 02:08:13 +00001274/*
1275** Close a file descriptor.
1276**
1277** We assume that close() almost always works, since it is only in a
1278** very sick application or on a very sick platform that it might fail.
1279** If it does fail, simply leak the file descriptor, but do log the
1280** error.
1281**
1282** Note that it is not safe to retry close() after EINTR since the
1283** file descriptor might have already been reused by another thread.
1284** So we don't even try to recover from an EINTR. Just log the error
1285** and move on.
1286*/
1287static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001288 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001289 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1290 pFile ? pFile->zPath : 0, lineno);
1291 }
1292}
dane18d4952011-02-21 11:46:24 +00001293
1294/*
drhe6d41732015-02-21 00:49:00 +00001295** Set the pFile->lastErrno. Do this in a subroutine as that provides
1296** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001297*/
1298static void storeLastErrno(unixFile *pFile, int error){
1299 pFile->lastErrno = error;
1300}
1301
1302/*
danb0ac3e32010-06-16 10:55:42 +00001303** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001304*/
drh0e9365c2011-03-02 02:08:13 +00001305static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001306 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001307 UnixUnusedFd *p;
1308 UnixUnusedFd *pNext;
drhef52b362018-08-13 22:50:34 +00001309 assert( unixFileMutexHeld(pFile) );
danb0ac3e32010-06-16 10:55:42 +00001310 for(p=pInode->pUnused; p; p=pNext){
1311 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001312 robust_close(pFile, p->fd, __LINE__);
1313 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001314 }
drh0e9365c2011-03-02 02:08:13 +00001315 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001316}
1317
1318/*
drh8af6c222010-05-14 12:43:01 +00001319** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001320**
drh24efa542018-10-02 19:36:40 +00001321** The global mutex must be held when this routine is called, but the mutex
1322** on the inode being deleted must NOT be held.
drh6c7d5c52008-11-21 20:32:33 +00001323*/
danb0ac3e32010-06-16 10:55:42 +00001324static void releaseInodeInfo(unixFile *pFile){
1325 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001326 assert( unixMutexHeld() );
drh095908e2018-08-13 20:46:18 +00001327 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00001328 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001329 pInode->nRef--;
1330 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001331 assert( pInode->pShmNode==0 );
drhef52b362018-08-13 22:50:34 +00001332 sqlite3_mutex_enter(pInode->pLockMutex);
danb0ac3e32010-06-16 10:55:42 +00001333 closePendingFds(pFile);
drhef52b362018-08-13 22:50:34 +00001334 sqlite3_mutex_leave(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001335 if( pInode->pPrev ){
1336 assert( pInode->pPrev->pNext==pInode );
1337 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001338 }else{
drh8af6c222010-05-14 12:43:01 +00001339 assert( inodeList==pInode );
1340 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001341 }
drh8af6c222010-05-14 12:43:01 +00001342 if( pInode->pNext ){
1343 assert( pInode->pNext->pPrev==pInode );
1344 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001345 }
drhda6dc242018-07-23 21:10:37 +00001346 sqlite3_mutex_free(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001347 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001348 }
drhbbd42a62004-05-22 17:41:58 +00001349 }
1350}
1351
1352/*
drh8af6c222010-05-14 12:43:01 +00001353** Given a file descriptor, locate the unixInodeInfo object that
1354** describes that file descriptor. Create a new one if necessary. The
1355** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001356**
drh24efa542018-10-02 19:36:40 +00001357** The global mutex must held when calling this routine.
dan9359c7b2009-08-21 08:29:10 +00001358**
drh6c7d5c52008-11-21 20:32:33 +00001359** Return an appropriate error code.
1360*/
drh8af6c222010-05-14 12:43:01 +00001361static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001362 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001363 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001364){
1365 int rc; /* System call return code */
1366 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001367 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1368 struct stat statbuf; /* Low-level file information */
1369 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001370
dan9359c7b2009-08-21 08:29:10 +00001371 assert( unixMutexHeld() );
1372
drh6c7d5c52008-11-21 20:32:33 +00001373 /* Get low-level information about the file that we can used to
1374 ** create a unique name for the file.
1375 */
1376 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001377 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001378 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001379 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001380#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001381 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1382#endif
1383 return SQLITE_IOERR;
1384 }
1385
drheb0d74f2009-02-03 15:27:02 +00001386#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001387 /* On OS X on an msdos filesystem, the inode number is reported
1388 ** incorrectly for zero-size files. See ticket #3260. To work
1389 ** around this problem (we consider it a bug in OS X, not SQLite)
1390 ** we always increase the file size to 1 by writing a single byte
1391 ** prior to accessing the inode number. The one byte written is
1392 ** an ASCII 'S' character which also happens to be the first byte
1393 ** in the header of every SQLite database. In this way, if there
1394 ** is a race condition such that another thread has already populated
1395 ** the first page of the database, no damage is done.
1396 */
drh7ed97b92010-01-20 13:07:21 +00001397 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001398 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001399 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001400 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001401 return SQLITE_IOERR;
1402 }
drh99ab3b12011-03-02 15:09:07 +00001403 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001404 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001405 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001406 return SQLITE_IOERR;
1407 }
1408 }
drheb0d74f2009-02-03 15:27:02 +00001409#endif
drh6c7d5c52008-11-21 20:32:33 +00001410
drh8af6c222010-05-14 12:43:01 +00001411 memset(&fileId, 0, sizeof(fileId));
1412 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001413#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001414 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001415#else
drh25ef7f52016-12-05 20:06:45 +00001416 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001417#endif
drh24efa542018-10-02 19:36:40 +00001418 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001419 pInode = inodeList;
1420 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1421 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001422 }
drh8af6c222010-05-14 12:43:01 +00001423 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001424 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001425 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001426 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001427 }
drh8af6c222010-05-14 12:43:01 +00001428 memset(pInode, 0, sizeof(*pInode));
1429 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
drh6886d6d2018-07-23 22:55:10 +00001430 if( sqlite3GlobalConfig.bCoreMutex ){
1431 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1432 if( pInode->pLockMutex==0 ){
1433 sqlite3_free(pInode);
1434 return SQLITE_NOMEM_BKPT;
1435 }
1436 }
drh8af6c222010-05-14 12:43:01 +00001437 pInode->nRef = 1;
drh24efa542018-10-02 19:36:40 +00001438 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001439 pInode->pNext = inodeList;
1440 pInode->pPrev = 0;
1441 if( inodeList ) inodeList->pPrev = pInode;
1442 inodeList = pInode;
1443 }else{
1444 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001445 }
drh8af6c222010-05-14 12:43:01 +00001446 *ppInode = pInode;
1447 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001448}
drh6c7d5c52008-11-21 20:32:33 +00001449
drhb959a012013-12-07 12:29:22 +00001450/*
1451** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1452*/
1453static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001454#if OS_VXWORKS
1455 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1456#else
drhb959a012013-12-07 12:29:22 +00001457 struct stat buf;
1458 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001459 (osStat(pFile->zPath, &buf)!=0
1460 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001461#endif
drhb959a012013-12-07 12:29:22 +00001462}
1463
aswift5b1a2562008-08-22 00:22:35 +00001464
1465/*
drhfbc7e882013-04-11 01:16:15 +00001466** Check a unixFile that is a database. Verify the following:
1467**
1468** (1) There is exactly one hard link on the file
1469** (2) The file is not a symbolic link
1470** (3) The file has not been renamed or unlinked
1471**
1472** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1473*/
1474static void verifyDbFile(unixFile *pFile){
1475 struct stat buf;
1476 int rc;
drh86151e82015-12-08 14:37:16 +00001477
1478 /* These verifications occurs for the main database only */
1479 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1480
drhfbc7e882013-04-11 01:16:15 +00001481 rc = osFstat(pFile->h, &buf);
1482 if( rc!=0 ){
1483 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001484 return;
1485 }
drh6369bc32016-03-21 16:06:42 +00001486 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001487 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001488 return;
1489 }
1490 if( buf.st_nlink>1 ){
1491 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001492 return;
1493 }
drhb959a012013-12-07 12:29:22 +00001494 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001495 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001496 return;
1497 }
1498}
1499
1500
1501/*
danielk197713adf8a2004-06-03 16:08:41 +00001502** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001503** file by this or any other process. If such a lock is held, set *pResOut
1504** to a non-zero value otherwise *pResOut is set to zero. The return value
1505** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001506*/
danielk1977861f7452008-06-05 11:39:11 +00001507static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001508 int rc = SQLITE_OK;
1509 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001510 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001511
danielk1977861f7452008-06-05 11:39:11 +00001512 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1513
drh054889e2005-11-30 03:20:31 +00001514 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001515 assert( pFile->eFileLock<=SHARED_LOCK );
drhda6dc242018-07-23 21:10:37 +00001516 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
danielk197713adf8a2004-06-03 16:08:41 +00001517
1518 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001519 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001520 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001521 }
1522
drh2ac3ee92004-06-07 16:27:46 +00001523 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001524 */
danielk197709480a92009-02-09 05:32:32 +00001525#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001526 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001527 struct flock lock;
1528 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001529 lock.l_start = RESERVED_BYTE;
1530 lock.l_len = 1;
1531 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001532 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1533 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001534 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001535 } else if( lock.l_type!=F_UNLCK ){
1536 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001537 }
1538 }
danielk197709480a92009-02-09 05:32:32 +00001539#endif
danielk197713adf8a2004-06-03 16:08:41 +00001540
drhda6dc242018-07-23 21:10:37 +00001541 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001542 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001543
aswift5b1a2562008-08-22 00:22:35 +00001544 *pResOut = reserved;
1545 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001546}
1547
1548/*
drhf0119b22018-03-26 17:40:53 +00001549** Set a posix-advisory-lock.
1550**
1551** There are two versions of this routine. If compiled with
1552** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1553** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1554** value is set, then it is the number of milliseconds to wait before
1555** failing the lock. The iBusyTimeout value is always reset back to
1556** zero on each call.
1557**
1558** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1559** attempt to set the lock.
1560*/
1561#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1562# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1563#else
1564static int osSetPosixAdvisoryLock(
1565 int h, /* The file descriptor on which to take the lock */
1566 struct flock *pLock, /* The description of the lock */
1567 unixFile *pFile /* Structure holding timeout value */
1568){
dan7bb8b8a2020-05-06 20:27:18 +00001569 int tm = pFile->iBusyTimeout;
drhf0119b22018-03-26 17:40:53 +00001570 int rc = osFcntl(h,F_SETLK,pLock);
dan7bb8b8a2020-05-06 20:27:18 +00001571 while( rc<0 && tm>0 ){
drhf0119b22018-03-26 17:40:53 +00001572 /* On systems that support some kind of blocking file lock with a timeout,
1573 ** make appropriate changes here to invoke that blocking file lock. On
1574 ** generic posix, however, there is no such API. So we simply try the
1575 ** lock once every millisecond until either the timeout expires, or until
1576 ** the lock is obtained. */
drhfd725632018-03-26 20:43:05 +00001577 usleep(1000);
1578 rc = osFcntl(h,F_SETLK,pLock);
dan7bb8b8a2020-05-06 20:27:18 +00001579 tm--;
drhf0119b22018-03-26 17:40:53 +00001580 }
1581 return rc;
1582}
1583#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1584
1585
1586/*
drha7e61d82011-03-12 17:02:57 +00001587** Attempt to set a system-lock on the file pFile. The lock is
1588** described by pLock.
1589**
drh77197112011-03-15 19:08:48 +00001590** If the pFile was opened read/write from unix-excl, then the only lock
1591** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001592** the first time any lock is attempted. All subsequent system locking
1593** operations become no-ops. Locking operations still happen internally,
1594** in order to coordinate access between separate database connections
1595** within this process, but all of that is handled in memory and the
1596** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001597**
1598** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1599** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1600** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001601**
1602** Zero is returned if the call completes successfully, or -1 if a call
1603** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001604*/
1605static int unixFileLock(unixFile *pFile, struct flock *pLock){
1606 int rc;
drh3cb93392011-03-12 18:10:44 +00001607 unixInodeInfo *pInode = pFile->pInode;
drh3cb93392011-03-12 18:10:44 +00001608 assert( pInode!=0 );
drhda6dc242018-07-23 21:10:37 +00001609 assert( sqlite3_mutex_held(pInode->pLockMutex) );
drh50358ad2015-12-02 01:04:33 +00001610 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001611 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001612 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001613 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001614 lock.l_whence = SEEK_SET;
1615 lock.l_start = SHARED_FIRST;
1616 lock.l_len = SHARED_SIZE;
1617 lock.l_type = F_WRLCK;
drhf0119b22018-03-26 17:40:53 +00001618 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
drha7e61d82011-03-12 17:02:57 +00001619 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001620 pInode->bProcessLock = 1;
1621 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001622 }else{
1623 rc = 0;
1624 }
1625 }else{
drhf0119b22018-03-26 17:40:53 +00001626 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
drha7e61d82011-03-12 17:02:57 +00001627 }
1628 return rc;
1629}
1630
1631/*
drh308c2a52010-05-14 11:30:18 +00001632** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001633** of the following:
1634**
drh2ac3ee92004-06-07 16:27:46 +00001635** (1) SHARED_LOCK
1636** (2) RESERVED_LOCK
1637** (3) PENDING_LOCK
1638** (4) EXCLUSIVE_LOCK
1639**
drhb3e04342004-06-08 00:47:47 +00001640** Sometimes when requesting one lock state, additional lock states
1641** are inserted in between. The locking might fail on one of the later
1642** transitions leaving the lock state different from what it started but
1643** still short of its goal. The following chart shows the allowed
1644** transitions and the inserted intermediate states:
1645**
1646** UNLOCKED -> SHARED
1647** SHARED -> RESERVED
1648** SHARED -> (PENDING) -> EXCLUSIVE
1649** RESERVED -> (PENDING) -> EXCLUSIVE
1650** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001651**
drha6abd042004-06-09 17:37:22 +00001652** This routine will only increase a lock. Use the sqlite3OsUnlock()
1653** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001654*/
drh308c2a52010-05-14 11:30:18 +00001655static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001656 /* The following describes the implementation of the various locks and
1657 ** lock transitions in terms of the POSIX advisory shared and exclusive
1658 ** lock primitives (called read-locks and write-locks below, to avoid
1659 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001660 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001661 ** accessing the same database file, in case that is ever required.
1662 **
1663 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1664 ** byte', each single bytes at well known offsets, and the 'shared byte
1665 ** range', a range of 510 bytes at a well known offset.
1666 **
1667 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001668 ** byte'. If this is successful, 'shared byte range' is read-locked
1669 ** and the lock on the 'pending byte' released. (Legacy note: When
1670 ** SQLite was first developed, Windows95 systems were still very common,
1671 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1672 ** single randomly selected by from the 'shared byte range' is locked.
1673 ** Windows95 is now pretty much extinct, but this work-around for the
1674 ** lack of shared-locks on Windows95 lives on, for backwards
1675 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001676 **
danielk197790ba3bd2004-06-25 08:32:25 +00001677 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1678 ** A RESERVED lock is implemented by grabbing a write-lock on the
1679 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001680 **
1681 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001682 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1683 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1684 ** obtained, but existing SHARED locks are allowed to persist. A process
1685 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1686 ** This property is used by the algorithm for rolling back a journal file
1687 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001688 **
danielk197790ba3bd2004-06-25 08:32:25 +00001689 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1690 ** implemented by obtaining a write-lock on the entire 'shared byte
1691 ** range'. Since all other locks require a read-lock on one of the bytes
1692 ** within this range, this ensures that no other locks are held on the
1693 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001694 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001695 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001696 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001697 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001698 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001699 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001700
drh054889e2005-11-30 03:20:31 +00001701 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001702 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1703 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001704 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001705 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001706
1707 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001708 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001709 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001710 */
drh308c2a52010-05-14 11:30:18 +00001711 if( pFile->eFileLock>=eFileLock ){
1712 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1713 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001714 return SQLITE_OK;
1715 }
1716
drh0c2694b2009-09-03 16:23:44 +00001717 /* Make sure the locking sequence is correct.
1718 ** (1) We never move from unlocked to anything higher than shared lock.
1719 ** (2) SQLite never explicitly requests a pendig lock.
1720 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001721 */
drh308c2a52010-05-14 11:30:18 +00001722 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1723 assert( eFileLock!=PENDING_LOCK );
1724 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001725
drh8af6c222010-05-14 12:43:01 +00001726 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001727 */
drh8af6c222010-05-14 12:43:01 +00001728 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001729 sqlite3_mutex_enter(pInode->pLockMutex);
drh029b44b2006-01-15 00:13:15 +00001730
danielk1977ad94b582007-08-20 06:44:22 +00001731 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001732 ** handle that precludes the requested lock, return BUSY.
1733 */
drh8af6c222010-05-14 12:43:01 +00001734 if( (pFile->eFileLock!=pInode->eFileLock &&
1735 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001736 ){
1737 rc = SQLITE_BUSY;
1738 goto end_lock;
1739 }
1740
1741 /* If a SHARED lock is requested, and some thread using this PID already
1742 ** has a SHARED or RESERVED lock, then increment reference counts and
1743 ** return SQLITE_OK.
1744 */
drh308c2a52010-05-14 11:30:18 +00001745 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001746 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001747 assert( eFileLock==SHARED_LOCK );
1748 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001749 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001750 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001751 pInode->nShared++;
1752 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001753 goto end_lock;
1754 }
1755
danielk19779a1d0ab2004-06-01 14:09:28 +00001756
drh3cde3bb2004-06-12 02:17:14 +00001757 /* A PENDING lock is needed before acquiring a SHARED lock and before
1758 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1759 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001760 */
drh0c2694b2009-09-03 16:23:44 +00001761 lock.l_len = 1L;
1762 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001763 if( eFileLock==SHARED_LOCK
1764 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001765 ){
drh308c2a52010-05-14 11:30:18 +00001766 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001767 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001768 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001769 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001770 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001771 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001772 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001773 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001774 goto end_lock;
1775 }
drh3cde3bb2004-06-12 02:17:14 +00001776 }
1777
1778
1779 /* If control gets to this point, then actually go ahead and make
1780 ** operating system calls for the specified lock.
1781 */
drh308c2a52010-05-14 11:30:18 +00001782 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001783 assert( pInode->nShared==0 );
1784 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001785 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001786
drh2ac3ee92004-06-07 16:27:46 +00001787 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001788 lock.l_start = SHARED_FIRST;
1789 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001790 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001791 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001792 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001793 }
dan661d71a2011-03-30 19:08:03 +00001794
drh2ac3ee92004-06-07 16:27:46 +00001795 /* Drop the temporary PENDING lock */
1796 lock.l_start = PENDING_BYTE;
1797 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001798 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001799 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1800 /* This could happen with a network mount */
1801 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001802 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001803 }
dan661d71a2011-03-30 19:08:03 +00001804
1805 if( rc ){
1806 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001807 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001808 }
dan661d71a2011-03-30 19:08:03 +00001809 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001810 }else{
drh308c2a52010-05-14 11:30:18 +00001811 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001812 pInode->nLock++;
1813 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001814 }
drh8af6c222010-05-14 12:43:01 +00001815 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001816 /* We are trying for an exclusive lock but another thread in this
1817 ** same process is still holding a shared lock. */
1818 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001819 }else{
drh3cde3bb2004-06-12 02:17:14 +00001820 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001821 ** assumed that there is a SHARED or greater lock on the file
1822 ** already.
1823 */
drh308c2a52010-05-14 11:30:18 +00001824 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001825 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001826
1827 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1828 if( eFileLock==RESERVED_LOCK ){
1829 lock.l_start = RESERVED_BYTE;
1830 lock.l_len = 1L;
1831 }else{
1832 lock.l_start = SHARED_FIRST;
1833 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001834 }
dan661d71a2011-03-30 19:08:03 +00001835
1836 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001837 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001838 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001839 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001840 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001841 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001842 }
drhbbd42a62004-05-22 17:41:58 +00001843 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001844
drh8f941bc2009-01-14 23:03:40 +00001845
drhd3d8c042012-05-29 17:02:40 +00001846#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001847 /* Set up the transaction-counter change checking flags when
1848 ** transitioning from a SHARED to a RESERVED lock. The change
1849 ** from SHARED to RESERVED marks the beginning of a normal
1850 ** write operation (not a hot journal rollback).
1851 */
1852 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001853 && pFile->eFileLock<=SHARED_LOCK
1854 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001855 ){
1856 pFile->transCntrChng = 0;
1857 pFile->dbUpdate = 0;
1858 pFile->inNormalWrite = 1;
1859 }
1860#endif
1861
1862
danielk1977ecb2a962004-06-02 06:30:16 +00001863 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001864 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001865 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001866 }else if( eFileLock==EXCLUSIVE_LOCK ){
1867 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001868 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001869 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001870
1871end_lock:
drhda6dc242018-07-23 21:10:37 +00001872 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001873 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1874 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001875 return rc;
1876}
1877
1878/*
dan08da86a2009-08-21 17:18:03 +00001879** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001880** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001881*/
1882static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001883 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001884 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drhef52b362018-08-13 22:50:34 +00001885 assert( unixFileMutexHeld(pFile) );
drh8af6c222010-05-14 12:43:01 +00001886 p->pNext = pInode->pUnused;
1887 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001888 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001889 pFile->pPreallocatedUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001890}
1891
1892/*
drh308c2a52010-05-14 11:30:18 +00001893** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001894** must be either NO_LOCK or SHARED_LOCK.
1895**
1896** If the locking level of the file descriptor is already at or below
1897** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001898**
1899** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1900** the byte range is divided into 2 parts and the first part is unlocked then
1901** set to a read lock, then the other part is simply unlocked. This works
1902** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1903** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001904*/
drha7e61d82011-03-12 17:02:57 +00001905static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001906 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001907 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001908 struct flock lock;
1909 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001910
drh054889e2005-11-30 03:20:31 +00001911 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001912 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001913 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001914 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001915
drh308c2a52010-05-14 11:30:18 +00001916 assert( eFileLock<=SHARED_LOCK );
1917 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001918 return SQLITE_OK;
1919 }
drh8af6c222010-05-14 12:43:01 +00001920 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001921 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001922 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001923 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001924 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001925
drhd3d8c042012-05-29 17:02:40 +00001926#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001927 /* When reducing a lock such that other processes can start
1928 ** reading the database file again, make sure that the
1929 ** transaction counter was updated if any part of the database
1930 ** file changed. If the transaction counter is not updated,
1931 ** other connections to the same file might not realize that
1932 ** the file has changed and hence might not know to flush their
1933 ** cache. The use of a stale cache can lead to database corruption.
1934 */
drh8f941bc2009-01-14 23:03:40 +00001935 pFile->inNormalWrite = 0;
1936#endif
1937
drh7ed97b92010-01-20 13:07:21 +00001938 /* downgrading to a shared lock on NFS involves clearing the write lock
1939 ** before establishing the readlock - to avoid a race condition we downgrade
1940 ** the lock in 2 blocks, so that part of the range will be covered by a
1941 ** write lock until the rest is covered by a read lock:
1942 ** 1: [WWWWW]
1943 ** 2: [....W]
1944 ** 3: [RRRRW]
1945 ** 4: [RRRR.]
1946 */
drh308c2a52010-05-14 11:30:18 +00001947 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001948#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001949 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001950 assert( handleNFSUnlock==0 );
1951#endif
1952#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001953 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001954 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001955 off_t divSize = SHARED_SIZE - 1;
1956
1957 lock.l_type = F_UNLCK;
1958 lock.l_whence = SEEK_SET;
1959 lock.l_start = SHARED_FIRST;
1960 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001961 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001962 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001963 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001964 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001965 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001966 }
drh7ed97b92010-01-20 13:07:21 +00001967 lock.l_type = F_RDLCK;
1968 lock.l_whence = SEEK_SET;
1969 lock.l_start = SHARED_FIRST;
1970 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001971 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001972 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001973 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1974 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001975 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001976 }
1977 goto end_unlock;
1978 }
1979 lock.l_type = F_UNLCK;
1980 lock.l_whence = SEEK_SET;
1981 lock.l_start = SHARED_FIRST+divSize;
1982 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001983 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001984 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001985 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001986 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001987 goto end_unlock;
1988 }
drh30f776f2011-02-25 03:25:07 +00001989 }else
1990#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1991 {
drh7ed97b92010-01-20 13:07:21 +00001992 lock.l_type = F_RDLCK;
1993 lock.l_whence = SEEK_SET;
1994 lock.l_start = SHARED_FIRST;
1995 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001996 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001997 /* In theory, the call to unixFileLock() cannot fail because another
1998 ** process is holding an incompatible lock. If it does, this
1999 ** indicates that the other process is not following the locking
2000 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
2001 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2002 ** an assert to fail). */
2003 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002004 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00002005 goto end_unlock;
2006 }
drh9c105bb2004-10-02 20:38:28 +00002007 }
2008 }
drhbbd42a62004-05-22 17:41:58 +00002009 lock.l_type = F_UNLCK;
2010 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00002011 lock.l_start = PENDING_BYTE;
2012 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00002013 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002014 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002015 }else{
danea83bc62011-04-01 11:56:32 +00002016 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002017 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00002018 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00002019 }
drhbbd42a62004-05-22 17:41:58 +00002020 }
drh308c2a52010-05-14 11:30:18 +00002021 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00002022 /* Decrement the shared lock counter. Release the lock using an
2023 ** OS call only when all threads in this same process have released
2024 ** the lock.
2025 */
drh8af6c222010-05-14 12:43:01 +00002026 pInode->nShared--;
2027 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00002028 lock.l_type = F_UNLCK;
2029 lock.l_whence = SEEK_SET;
2030 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00002031 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002032 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002033 }else{
danea83bc62011-04-01 11:56:32 +00002034 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002035 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00002036 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002037 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002038 }
drha6abd042004-06-09 17:37:22 +00002039 }
2040
drhbbd42a62004-05-22 17:41:58 +00002041 /* Decrement the count of locks against this same file. When the
2042 ** count reaches zero, close any other file descriptors whose close
2043 ** was deferred because of outstanding locks.
2044 */
drh8af6c222010-05-14 12:43:01 +00002045 pInode->nLock--;
2046 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00002047 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00002048 }
drhf2f105d2012-08-20 15:53:54 +00002049
aswift5b1a2562008-08-22 00:22:35 +00002050end_unlock:
drhda6dc242018-07-23 21:10:37 +00002051 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00002052 if( rc==SQLITE_OK ){
2053 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00002054 }
drh9c105bb2004-10-02 20:38:28 +00002055 return rc;
drhbbd42a62004-05-22 17:41:58 +00002056}
2057
2058/*
drh308c2a52010-05-14 11:30:18 +00002059** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002060** must be either NO_LOCK or SHARED_LOCK.
2061**
2062** If the locking level of the file descriptor is already at or below
2063** the requested locking level, this routine is a no-op.
2064*/
drh308c2a52010-05-14 11:30:18 +00002065static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00002066#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00002067 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00002068#endif
drha7e61d82011-03-12 17:02:57 +00002069 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00002070}
2071
mistachkine98844f2013-08-24 00:59:24 +00002072#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002073static int unixMapfile(unixFile *pFd, i64 nByte);
2074static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00002075#endif
danf23da962013-03-23 21:00:41 +00002076
drh7ed97b92010-01-20 13:07:21 +00002077/*
danielk1977e339d652008-06-28 11:23:00 +00002078** This function performs the parts of the "close file" operation
2079** common to all locking schemes. It closes the directory and file
2080** handles, if they are valid, and sets all fields of the unixFile
2081** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00002082**
2083** It is *not* necessary to hold the mutex when this routine is called,
2084** even on VxWorks. A mutex will be acquired on VxWorks by the
2085** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00002086*/
2087static int closeUnixFile(sqlite3_file *id){
2088 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00002089#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002090 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00002091#endif
dan661d71a2011-03-30 19:08:03 +00002092 if( pFile->h>=0 ){
2093 robust_close(pFile, pFile->h, __LINE__);
2094 pFile->h = -1;
2095 }
2096#if OS_VXWORKS
2097 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00002098 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00002099 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00002100 }
2101 vxworksReleaseFileId(pFile->pId);
2102 pFile->pId = 0;
2103 }
2104#endif
drh0bdbc902014-06-16 18:35:06 +00002105#ifdef SQLITE_UNLINK_AFTER_CLOSE
2106 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2107 osUnlink(pFile->zPath);
2108 sqlite3_free(*(char**)&pFile->zPath);
2109 pFile->zPath = 0;
2110 }
2111#endif
dan661d71a2011-03-30 19:08:03 +00002112 OSTRACE(("CLOSE %-3d\n", pFile->h));
2113 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00002114 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00002115 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00002116 return SQLITE_OK;
2117}
2118
2119/*
danielk1977e3026632004-06-22 11:29:02 +00002120** Close a file.
2121*/
danielk197762079062007-08-15 17:08:46 +00002122static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002123 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002124 unixFile *pFile = (unixFile *)id;
drhef52b362018-08-13 22:50:34 +00002125 unixInodeInfo *pInode = pFile->pInode;
2126
2127 assert( pInode!=0 );
drhfbc7e882013-04-11 01:16:15 +00002128 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002129 unixUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00002130 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00002131 unixEnterMutex();
2132
2133 /* unixFile.pInode is always valid here. Otherwise, a different close
2134 ** routine (e.g. nolockClose()) would be called instead.
2135 */
2136 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
drhef52b362018-08-13 22:50:34 +00002137 sqlite3_mutex_enter(pInode->pLockMutex);
drh3fcef1a2018-08-16 16:24:24 +00002138 if( pInode->nLock ){
dan661d71a2011-03-30 19:08:03 +00002139 /* If there are outstanding locks, do not actually close the file just
2140 ** yet because that would clear those locks. Instead, add the file
2141 ** descriptor to pInode->pUnused list. It will be automatically closed
2142 ** when the last lock is cleared.
2143 */
2144 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002145 }
drhef52b362018-08-13 22:50:34 +00002146 sqlite3_mutex_leave(pInode->pLockMutex);
dan661d71a2011-03-30 19:08:03 +00002147 releaseInodeInfo(pFile);
2148 rc = closeUnixFile(id);
2149 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002150 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002151}
2152
drh734c9862008-11-28 15:37:20 +00002153/************** End of the posix advisory lock implementation *****************
2154******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002155
drh734c9862008-11-28 15:37:20 +00002156/******************************************************************************
2157****************************** No-op Locking **********************************
2158**
2159** Of the various locking implementations available, this is by far the
2160** simplest: locking is ignored. No attempt is made to lock the database
2161** file for reading or writing.
2162**
2163** This locking mode is appropriate for use on read-only databases
2164** (ex: databases that are burned into CD-ROM, for example.) It can
2165** also be used if the application employs some external mechanism to
2166** prevent simultaneous access of the same database by two or more
2167** database connections. But there is a serious risk of database
2168** corruption if this locking mode is used in situations where multiple
2169** database connections are accessing the same database file at the same
2170** time and one or more of those connections are writing.
2171*/
drhbfe66312006-10-03 17:40:40 +00002172
drh734c9862008-11-28 15:37:20 +00002173static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2174 UNUSED_PARAMETER(NotUsed);
2175 *pResOut = 0;
2176 return SQLITE_OK;
2177}
drh734c9862008-11-28 15:37:20 +00002178static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2179 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2180 return SQLITE_OK;
2181}
drh734c9862008-11-28 15:37:20 +00002182static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2183 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2184 return SQLITE_OK;
2185}
2186
2187/*
drh9b35ea62008-11-29 02:20:26 +00002188** Close the file.
drh734c9862008-11-28 15:37:20 +00002189*/
2190static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002191 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002192}
2193
2194/******************* End of the no-op lock implementation *********************
2195******************************************************************************/
2196
2197/******************************************************************************
2198************************* Begin dot-file Locking ******************************
2199**
mistachkin48864df2013-03-21 21:20:32 +00002200** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002201** files (really a directory) to control access to the database. This works
2202** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002203**
2204** (1) There is zero concurrency. A single reader blocks all other
2205** connections from reading or writing the database.
2206**
2207** (2) An application crash or power loss can leave stale lock files
2208** sitting around that need to be cleared manually.
2209**
2210** Nevertheless, a dotlock is an appropriate locking mode for use if no
2211** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002212**
drh9ef6bc42011-11-04 02:24:02 +00002213** Dotfile locking works by creating a subdirectory in the same directory as
2214** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002215** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002216** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002217*/
2218
2219/*
2220** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002221** lock directory.
drh734c9862008-11-28 15:37:20 +00002222*/
2223#define DOTLOCK_SUFFIX ".lock"
2224
drh7708e972008-11-29 00:56:52 +00002225/*
2226** This routine checks if there is a RESERVED lock held on the specified
2227** file by this or any other process. If such a lock is held, set *pResOut
2228** to a non-zero value otherwise *pResOut is set to zero. The return value
2229** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2230**
2231** In dotfile locking, either a lock exists or it does not. So in this
2232** variation of CheckReservedLock(), *pResOut is set to true if any lock
2233** is held on the file and false if the file is unlocked.
2234*/
drh734c9862008-11-28 15:37:20 +00002235static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2236 int rc = SQLITE_OK;
2237 int reserved = 0;
2238 unixFile *pFile = (unixFile*)id;
2239
2240 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2241
2242 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002243 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002244 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002245 *pResOut = reserved;
2246 return rc;
2247}
2248
drh7708e972008-11-29 00:56:52 +00002249/*
drh308c2a52010-05-14 11:30:18 +00002250** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002251** of the following:
2252**
2253** (1) SHARED_LOCK
2254** (2) RESERVED_LOCK
2255** (3) PENDING_LOCK
2256** (4) EXCLUSIVE_LOCK
2257**
2258** Sometimes when requesting one lock state, additional lock states
2259** are inserted in between. The locking might fail on one of the later
2260** transitions leaving the lock state different from what it started but
2261** still short of its goal. The following chart shows the allowed
2262** transitions and the inserted intermediate states:
2263**
2264** UNLOCKED -> SHARED
2265** SHARED -> RESERVED
2266** SHARED -> (PENDING) -> EXCLUSIVE
2267** RESERVED -> (PENDING) -> EXCLUSIVE
2268** PENDING -> EXCLUSIVE
2269**
2270** This routine will only increase a lock. Use the sqlite3OsUnlock()
2271** routine to lower a locking level.
2272**
2273** With dotfile locking, we really only support state (4): EXCLUSIVE.
2274** But we track the other locking levels internally.
2275*/
drh308c2a52010-05-14 11:30:18 +00002276static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002277 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002278 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002279 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002280
drh7708e972008-11-29 00:56:52 +00002281
2282 /* If we have any lock, then the lock file already exists. All we have
2283 ** to do is adjust our internal record of the lock level.
2284 */
drh308c2a52010-05-14 11:30:18 +00002285 if( pFile->eFileLock > NO_LOCK ){
2286 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002287 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002288#ifdef HAVE_UTIME
2289 utime(zLockFile, NULL);
2290#else
drh734c9862008-11-28 15:37:20 +00002291 utimes(zLockFile, NULL);
2292#endif
drh7708e972008-11-29 00:56:52 +00002293 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002294 }
2295
2296 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002297 rc = osMkdir(zLockFile, 0777);
2298 if( rc<0 ){
2299 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002300 int tErrno = errno;
2301 if( EEXIST == tErrno ){
2302 rc = SQLITE_BUSY;
2303 } else {
2304 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002305 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002306 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002307 }
2308 }
drh7708e972008-11-29 00:56:52 +00002309 return rc;
drh734c9862008-11-28 15:37:20 +00002310 }
drh734c9862008-11-28 15:37:20 +00002311
2312 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002313 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002314 return rc;
2315}
2316
drh7708e972008-11-29 00:56:52 +00002317/*
drh308c2a52010-05-14 11:30:18 +00002318** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002319** must be either NO_LOCK or SHARED_LOCK.
2320**
2321** If the locking level of the file descriptor is already at or below
2322** the requested locking level, this routine is a no-op.
2323**
2324** When the locking level reaches NO_LOCK, delete the lock file.
2325*/
drh308c2a52010-05-14 11:30:18 +00002326static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002327 unixFile *pFile = (unixFile*)id;
2328 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002329 int rc;
drh734c9862008-11-28 15:37:20 +00002330
2331 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002332 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002333 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002334 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002335
2336 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002337 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002338 return SQLITE_OK;
2339 }
drh7708e972008-11-29 00:56:52 +00002340
2341 /* To downgrade to shared, simply update our internal notion of the
2342 ** lock state. No need to mess with the file on disk.
2343 */
drh308c2a52010-05-14 11:30:18 +00002344 if( eFileLock==SHARED_LOCK ){
2345 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002346 return SQLITE_OK;
2347 }
2348
drh7708e972008-11-29 00:56:52 +00002349 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002350 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002351 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002352 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002353 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002354 if( tErrno==ENOENT ){
2355 rc = SQLITE_OK;
2356 }else{
danea83bc62011-04-01 11:56:32 +00002357 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002358 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002359 }
2360 return rc;
2361 }
drh308c2a52010-05-14 11:30:18 +00002362 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002363 return SQLITE_OK;
2364}
2365
2366/*
drh9b35ea62008-11-29 02:20:26 +00002367** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002368*/
2369static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002370 unixFile *pFile = (unixFile*)id;
2371 assert( id!=0 );
2372 dotlockUnlock(id, NO_LOCK);
2373 sqlite3_free(pFile->lockingContext);
2374 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002375}
2376/****************** End of the dot-file lock implementation *******************
2377******************************************************************************/
2378
2379/******************************************************************************
2380************************** Begin flock Locking ********************************
2381**
2382** Use the flock() system call to do file locking.
2383**
drh6b9d6dd2008-12-03 19:34:47 +00002384** flock() locking is like dot-file locking in that the various
2385** fine-grain locking levels supported by SQLite are collapsed into
2386** a single exclusive lock. In other words, SHARED, RESERVED, and
2387** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2388** still works when you do this, but concurrency is reduced since
2389** only a single process can be reading the database at a time.
2390**
drhe89b2912015-03-03 20:42:01 +00002391** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002392*/
drhe89b2912015-03-03 20:42:01 +00002393#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002394
drh6b9d6dd2008-12-03 19:34:47 +00002395/*
drhff812312011-02-23 13:33:46 +00002396** Retry flock() calls that fail with EINTR
2397*/
2398#ifdef EINTR
2399static int robust_flock(int fd, int op){
2400 int rc;
2401 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2402 return rc;
2403}
2404#else
drh5c819272011-02-23 14:00:12 +00002405# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002406#endif
2407
2408
2409/*
drh6b9d6dd2008-12-03 19:34:47 +00002410** This routine checks if there is a RESERVED lock held on the specified
2411** file by this or any other process. If such a lock is held, set *pResOut
2412** to a non-zero value otherwise *pResOut is set to zero. The return value
2413** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2414*/
drh734c9862008-11-28 15:37:20 +00002415static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2416 int rc = SQLITE_OK;
2417 int reserved = 0;
2418 unixFile *pFile = (unixFile*)id;
2419
2420 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2421
2422 assert( pFile );
2423
2424 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002425 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002426 reserved = 1;
2427 }
2428
2429 /* Otherwise see if some other process holds it. */
2430 if( !reserved ){
2431 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002432 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002433 if( !lrc ){
2434 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002435 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002436 if ( lrc ) {
2437 int tErrno = errno;
2438 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002439 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002440 storeLastErrno(pFile, tErrno);
2441 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002442 }
2443 } else {
2444 int tErrno = errno;
2445 reserved = 1;
2446 /* someone else might have it reserved */
2447 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2448 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002449 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002450 rc = lrc;
2451 }
2452 }
2453 }
drh308c2a52010-05-14 11:30:18 +00002454 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002455
2456#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002457 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002458 rc = SQLITE_OK;
2459 reserved=1;
2460 }
2461#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2462 *pResOut = reserved;
2463 return rc;
2464}
2465
drh6b9d6dd2008-12-03 19:34:47 +00002466/*
drh308c2a52010-05-14 11:30:18 +00002467** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002468** of the following:
2469**
2470** (1) SHARED_LOCK
2471** (2) RESERVED_LOCK
2472** (3) PENDING_LOCK
2473** (4) EXCLUSIVE_LOCK
2474**
2475** Sometimes when requesting one lock state, additional lock states
2476** are inserted in between. The locking might fail on one of the later
2477** transitions leaving the lock state different from what it started but
2478** still short of its goal. The following chart shows the allowed
2479** transitions and the inserted intermediate states:
2480**
2481** UNLOCKED -> SHARED
2482** SHARED -> RESERVED
2483** SHARED -> (PENDING) -> EXCLUSIVE
2484** RESERVED -> (PENDING) -> EXCLUSIVE
2485** PENDING -> EXCLUSIVE
2486**
2487** flock() only really support EXCLUSIVE locks. We track intermediate
2488** lock states in the sqlite3_file structure, but all locks SHARED or
2489** above are really EXCLUSIVE locks and exclude all other processes from
2490** access the file.
2491**
2492** This routine will only increase a lock. Use the sqlite3OsUnlock()
2493** routine to lower a locking level.
2494*/
drh308c2a52010-05-14 11:30:18 +00002495static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002496 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002497 unixFile *pFile = (unixFile*)id;
2498
2499 assert( pFile );
2500
2501 /* if we already have a lock, it is exclusive.
2502 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002503 if (pFile->eFileLock > NO_LOCK) {
2504 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002505 return SQLITE_OK;
2506 }
2507
2508 /* grab an exclusive lock */
2509
drhff812312011-02-23 13:33:46 +00002510 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002511 int tErrno = errno;
2512 /* didn't get, must be busy */
2513 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2514 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002515 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002516 }
2517 } else {
2518 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002519 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002520 }
drh308c2a52010-05-14 11:30:18 +00002521 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2522 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002523#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002524 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002525 rc = SQLITE_BUSY;
2526 }
2527#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2528 return rc;
2529}
2530
drh6b9d6dd2008-12-03 19:34:47 +00002531
2532/*
drh308c2a52010-05-14 11:30:18 +00002533** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002534** must be either NO_LOCK or SHARED_LOCK.
2535**
2536** If the locking level of the file descriptor is already at or below
2537** the requested locking level, this routine is a no-op.
2538*/
drh308c2a52010-05-14 11:30:18 +00002539static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002540 unixFile *pFile = (unixFile*)id;
2541
2542 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002543 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002544 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002545 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002546
2547 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002548 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002549 return SQLITE_OK;
2550 }
2551
2552 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002553 if (eFileLock==SHARED_LOCK) {
2554 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002555 return SQLITE_OK;
2556 }
2557
2558 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002559 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002560#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002561 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002562#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002563 return SQLITE_IOERR_UNLOCK;
2564 }else{
drh308c2a52010-05-14 11:30:18 +00002565 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002566 return SQLITE_OK;
2567 }
2568}
2569
2570/*
2571** Close a file.
2572*/
2573static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002574 assert( id!=0 );
2575 flockUnlock(id, NO_LOCK);
2576 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002577}
2578
2579#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2580
2581/******************* End of the flock lock implementation *********************
2582******************************************************************************/
2583
2584/******************************************************************************
2585************************ Begin Named Semaphore Locking ************************
2586**
2587** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002588**
2589** Semaphore locking is like dot-lock and flock in that it really only
2590** supports EXCLUSIVE locking. Only a single process can read or write
2591** the database file at a time. This reduces potential concurrency, but
2592** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002593*/
2594#if OS_VXWORKS
2595
drh6b9d6dd2008-12-03 19:34:47 +00002596/*
2597** This routine checks if there is a RESERVED lock held on the specified
2598** file by this or any other process. If such a lock is held, set *pResOut
2599** to a non-zero value otherwise *pResOut is set to zero. The return value
2600** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2601*/
drh8cd5b252015-03-02 22:06:43 +00002602static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002603 int rc = SQLITE_OK;
2604 int reserved = 0;
2605 unixFile *pFile = (unixFile*)id;
2606
2607 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2608
2609 assert( pFile );
2610
2611 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002612 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002613 reserved = 1;
2614 }
2615
2616 /* Otherwise see if some other process holds it. */
2617 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002618 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002619
2620 if( sem_trywait(pSem)==-1 ){
2621 int tErrno = errno;
2622 if( EAGAIN != tErrno ){
2623 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002624 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002625 } else {
2626 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002627 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002628 }
2629 }else{
2630 /* we could have it if we want it */
2631 sem_post(pSem);
2632 }
2633 }
drh308c2a52010-05-14 11:30:18 +00002634 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002635
2636 *pResOut = reserved;
2637 return rc;
2638}
2639
drh6b9d6dd2008-12-03 19:34:47 +00002640/*
drh308c2a52010-05-14 11:30:18 +00002641** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002642** of the following:
2643**
2644** (1) SHARED_LOCK
2645** (2) RESERVED_LOCK
2646** (3) PENDING_LOCK
2647** (4) EXCLUSIVE_LOCK
2648**
2649** Sometimes when requesting one lock state, additional lock states
2650** are inserted in between. The locking might fail on one of the later
2651** transitions leaving the lock state different from what it started but
2652** still short of its goal. The following chart shows the allowed
2653** transitions and the inserted intermediate states:
2654**
2655** UNLOCKED -> SHARED
2656** SHARED -> RESERVED
2657** SHARED -> (PENDING) -> EXCLUSIVE
2658** RESERVED -> (PENDING) -> EXCLUSIVE
2659** PENDING -> EXCLUSIVE
2660**
2661** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2662** lock states in the sqlite3_file structure, but all locks SHARED or
2663** above are really EXCLUSIVE locks and exclude all other processes from
2664** access the file.
2665**
2666** This routine will only increase a lock. Use the sqlite3OsUnlock()
2667** routine to lower a locking level.
2668*/
drh8cd5b252015-03-02 22:06:43 +00002669static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002670 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002671 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002672 int rc = SQLITE_OK;
2673
2674 /* if we already have a lock, it is exclusive.
2675 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002676 if (pFile->eFileLock > NO_LOCK) {
2677 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002678 rc = SQLITE_OK;
2679 goto sem_end_lock;
2680 }
2681
2682 /* lock semaphore now but bail out when already locked. */
2683 if( sem_trywait(pSem)==-1 ){
2684 rc = SQLITE_BUSY;
2685 goto sem_end_lock;
2686 }
2687
2688 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002689 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002690
2691 sem_end_lock:
2692 return rc;
2693}
2694
drh6b9d6dd2008-12-03 19:34:47 +00002695/*
drh308c2a52010-05-14 11:30:18 +00002696** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002697** must be either NO_LOCK or SHARED_LOCK.
2698**
2699** If the locking level of the file descriptor is already at or below
2700** the requested locking level, this routine is a no-op.
2701*/
drh8cd5b252015-03-02 22:06:43 +00002702static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002703 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002704 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002705
2706 assert( pFile );
2707 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002708 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002709 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002710 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002711
2712 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002713 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002714 return SQLITE_OK;
2715 }
2716
2717 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002718 if (eFileLock==SHARED_LOCK) {
2719 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002720 return SQLITE_OK;
2721 }
2722
2723 /* no, really unlock. */
2724 if ( sem_post(pSem)==-1 ) {
2725 int rc, tErrno = errno;
2726 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2727 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002728 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002729 }
2730 return rc;
2731 }
drh308c2a52010-05-14 11:30:18 +00002732 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002733 return SQLITE_OK;
2734}
2735
2736/*
2737 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002738 */
drh8cd5b252015-03-02 22:06:43 +00002739static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002740 if( id ){
2741 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002742 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002743 assert( pFile );
drh095908e2018-08-13 20:46:18 +00002744 assert( unixFileMutexNotheld(pFile) );
drh734c9862008-11-28 15:37:20 +00002745 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002746 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002747 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002748 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002749 }
2750 return SQLITE_OK;
2751}
2752
2753#endif /* OS_VXWORKS */
2754/*
2755** Named semaphore locking is only available on VxWorks.
2756**
2757*************** End of the named semaphore lock implementation ****************
2758******************************************************************************/
2759
2760
2761/******************************************************************************
2762*************************** Begin AFP Locking *********************************
2763**
2764** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2765** on Apple Macintosh computers - both OS9 and OSX.
2766**
2767** Third-party implementations of AFP are available. But this code here
2768** only works on OSX.
2769*/
2770
drhd2cb50b2009-01-09 21:41:17 +00002771#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002772/*
2773** The afpLockingContext structure contains all afp lock specific state
2774*/
drhbfe66312006-10-03 17:40:40 +00002775typedef struct afpLockingContext afpLockingContext;
2776struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002777 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002778 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002779};
2780
2781struct ByteRangeLockPB2
2782{
2783 unsigned long long offset; /* offset to first byte to lock */
2784 unsigned long long length; /* nbr of bytes to lock */
2785 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2786 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2787 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2788 int fd; /* file desc to assoc this lock with */
2789};
2790
drhfd131da2007-08-07 17:13:03 +00002791#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002792
drh6b9d6dd2008-12-03 19:34:47 +00002793/*
2794** This is a utility for setting or clearing a bit-range lock on an
2795** AFP filesystem.
2796**
2797** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2798*/
2799static int afpSetLock(
2800 const char *path, /* Name of the file to be locked or unlocked */
2801 unixFile *pFile, /* Open file descriptor on path */
2802 unsigned long long offset, /* First byte to be locked */
2803 unsigned long long length, /* Number of bytes to lock */
2804 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002805){
drh6b9d6dd2008-12-03 19:34:47 +00002806 struct ByteRangeLockPB2 pb;
2807 int err;
drhbfe66312006-10-03 17:40:40 +00002808
2809 pb.unLockFlag = setLockFlag ? 0 : 1;
2810 pb.startEndFlag = 0;
2811 pb.offset = offset;
2812 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002813 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002814
drh308c2a52010-05-14 11:30:18 +00002815 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002816 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002817 offset, length));
drhbfe66312006-10-03 17:40:40 +00002818 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2819 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002820 int rc;
2821 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002822 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2823 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002824#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2825 rc = SQLITE_BUSY;
2826#else
drh734c9862008-11-28 15:37:20 +00002827 rc = sqliteErrorFromPosixError(tErrno,
2828 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002829#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002830 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002831 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002832 }
2833 return rc;
drhbfe66312006-10-03 17:40:40 +00002834 } else {
aswift5b1a2562008-08-22 00:22:35 +00002835 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002836 }
2837}
2838
drh6b9d6dd2008-12-03 19:34:47 +00002839/*
2840** This routine checks if there is a RESERVED lock held on the specified
2841** file by this or any other process. If such a lock is held, set *pResOut
2842** to a non-zero value otherwise *pResOut is set to zero. The return value
2843** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2844*/
danielk1977e339d652008-06-28 11:23:00 +00002845static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002846 int rc = SQLITE_OK;
2847 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002848 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002849 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002850
aswift5b1a2562008-08-22 00:22:35 +00002851 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2852
2853 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002854 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002855 if( context->reserved ){
2856 *pResOut = 1;
2857 return SQLITE_OK;
2858 }
drhda6dc242018-07-23 21:10:37 +00002859 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
drhbfe66312006-10-03 17:40:40 +00002860 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002861 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002862 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002863 }
2864
2865 /* Otherwise see if some other process holds it.
2866 */
aswift5b1a2562008-08-22 00:22:35 +00002867 if( !reserved ){
2868 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002869 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002870 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002871 /* if we succeeded in taking the reserved lock, unlock it to restore
2872 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002873 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002874 } else {
2875 /* if we failed to get the lock then someone else must have it */
2876 reserved = 1;
2877 }
2878 if( IS_LOCK_ERROR(lrc) ){
2879 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002880 }
2881 }
drhbfe66312006-10-03 17:40:40 +00002882
drhda6dc242018-07-23 21:10:37 +00002883 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00002884 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002885
2886 *pResOut = reserved;
2887 return rc;
drhbfe66312006-10-03 17:40:40 +00002888}
2889
drh6b9d6dd2008-12-03 19:34:47 +00002890/*
drh308c2a52010-05-14 11:30:18 +00002891** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002892** of the following:
2893**
2894** (1) SHARED_LOCK
2895** (2) RESERVED_LOCK
2896** (3) PENDING_LOCK
2897** (4) EXCLUSIVE_LOCK
2898**
2899** Sometimes when requesting one lock state, additional lock states
2900** are inserted in between. The locking might fail on one of the later
2901** transitions leaving the lock state different from what it started but
2902** still short of its goal. The following chart shows the allowed
2903** transitions and the inserted intermediate states:
2904**
2905** UNLOCKED -> SHARED
2906** SHARED -> RESERVED
2907** SHARED -> (PENDING) -> EXCLUSIVE
2908** RESERVED -> (PENDING) -> EXCLUSIVE
2909** PENDING -> EXCLUSIVE
2910**
2911** This routine will only increase a lock. Use the sqlite3OsUnlock()
2912** routine to lower a locking level.
2913*/
drh308c2a52010-05-14 11:30:18 +00002914static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002915 int rc = SQLITE_OK;
2916 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002917 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002918 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002919
2920 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002921 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2922 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002923 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002924
drhbfe66312006-10-03 17:40:40 +00002925 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002926 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002927 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002928 */
drh308c2a52010-05-14 11:30:18 +00002929 if( pFile->eFileLock>=eFileLock ){
2930 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2931 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002932 return SQLITE_OK;
2933 }
2934
2935 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002936 ** (1) We never move from unlocked to anything higher than shared lock.
2937 ** (2) SQLite never explicitly requests a pendig lock.
2938 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002939 */
drh308c2a52010-05-14 11:30:18 +00002940 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2941 assert( eFileLock!=PENDING_LOCK );
2942 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002943
drh8af6c222010-05-14 12:43:01 +00002944 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002945 */
drh8af6c222010-05-14 12:43:01 +00002946 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00002947 sqlite3_mutex_enter(pInode->pLockMutex);
drh7ed97b92010-01-20 13:07:21 +00002948
2949 /* If some thread using this PID has a lock via a different unixFile*
2950 ** handle that precludes the requested lock, return BUSY.
2951 */
drh8af6c222010-05-14 12:43:01 +00002952 if( (pFile->eFileLock!=pInode->eFileLock &&
2953 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002954 ){
2955 rc = SQLITE_BUSY;
2956 goto afp_end_lock;
2957 }
2958
2959 /* If a SHARED lock is requested, and some thread using this PID already
2960 ** has a SHARED or RESERVED lock, then increment reference counts and
2961 ** return SQLITE_OK.
2962 */
drh308c2a52010-05-14 11:30:18 +00002963 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002964 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002965 assert( eFileLock==SHARED_LOCK );
2966 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002967 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002968 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002969 pInode->nShared++;
2970 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002971 goto afp_end_lock;
2972 }
drhbfe66312006-10-03 17:40:40 +00002973
2974 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002975 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2976 ** be released.
2977 */
drh308c2a52010-05-14 11:30:18 +00002978 if( eFileLock==SHARED_LOCK
2979 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002980 ){
2981 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002982 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002983 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002984 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002985 goto afp_end_lock;
2986 }
2987 }
2988
2989 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002990 ** operating system calls for the specified lock.
2991 */
drh308c2a52010-05-14 11:30:18 +00002992 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002993 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002994 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002995
drh8af6c222010-05-14 12:43:01 +00002996 assert( pInode->nShared==0 );
2997 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002998
2999 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00003000 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00003001 /* note that the quality of the randomness doesn't matter that much */
3002 lk = random();
drh8af6c222010-05-14 12:43:01 +00003003 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00003004 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003005 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00003006 if( IS_LOCK_ERROR(lrc1) ){
3007 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00003008 }
aswift5b1a2562008-08-22 00:22:35 +00003009 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00003010 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00003011
aswift5b1a2562008-08-22 00:22:35 +00003012 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00003013 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00003014 rc = lrc1;
3015 goto afp_end_lock;
3016 } else if( IS_LOCK_ERROR(lrc2) ){
3017 rc = lrc2;
3018 goto afp_end_lock;
3019 } else if( lrc1 != SQLITE_OK ) {
3020 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00003021 } else {
drh308c2a52010-05-14 11:30:18 +00003022 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00003023 pInode->nLock++;
3024 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00003025 }
drh8af6c222010-05-14 12:43:01 +00003026 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00003027 /* We are trying for an exclusive lock but another thread in this
3028 ** same process is still holding a shared lock. */
3029 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00003030 }else{
3031 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3032 ** assumed that there is a SHARED or greater lock on the file
3033 ** already.
3034 */
3035 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00003036 assert( 0!=pFile->eFileLock );
3037 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003038 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00003039 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00003040 if( !failed ){
3041 context->reserved = 1;
3042 }
drhbfe66312006-10-03 17:40:40 +00003043 }
drh308c2a52010-05-14 11:30:18 +00003044 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003045 /* Acquire an EXCLUSIVE lock */
3046
3047 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00003048 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00003049 */
drh6b9d6dd2008-12-03 19:34:47 +00003050 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00003051 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00003052 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00003053 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00003054 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00003055 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00003056 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003057 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00003058 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3059 ** a critical I/O error
3060 */
drh2e233812017-08-22 15:21:54 +00003061 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00003062 SQLITE_IOERR_LOCK;
3063 goto afp_end_lock;
3064 }
3065 }else{
aswift5b1a2562008-08-22 00:22:35 +00003066 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003067 }
3068 }
aswift5b1a2562008-08-22 00:22:35 +00003069 if( failed ){
3070 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003071 }
3072 }
3073
3074 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00003075 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00003076 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00003077 }else if( eFileLock==EXCLUSIVE_LOCK ){
3078 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00003079 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00003080 }
3081
3082afp_end_lock:
drhda6dc242018-07-23 21:10:37 +00003083 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00003084 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3085 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00003086 return rc;
3087}
3088
3089/*
drh308c2a52010-05-14 11:30:18 +00003090** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00003091** must be either NO_LOCK or SHARED_LOCK.
3092**
3093** If the locking level of the file descriptor is already at or below
3094** the requested locking level, this routine is a no-op.
3095*/
drh308c2a52010-05-14 11:30:18 +00003096static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00003097 int rc = SQLITE_OK;
3098 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00003099 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00003100 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3101 int skipShared = 0;
3102#ifdef SQLITE_TEST
3103 int h = pFile->h;
3104#endif
drhbfe66312006-10-03 17:40:40 +00003105
3106 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003107 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00003108 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00003109 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00003110
drh308c2a52010-05-14 11:30:18 +00003111 assert( eFileLock<=SHARED_LOCK );
3112 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00003113 return SQLITE_OK;
3114 }
drh8af6c222010-05-14 12:43:01 +00003115 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00003116 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00003117 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00003118 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00003119 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00003120 SimulateIOErrorBenign(1);
3121 SimulateIOError( h=(-1) )
3122 SimulateIOErrorBenign(0);
3123
drhd3d8c042012-05-29 17:02:40 +00003124#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003125 /* When reducing a lock such that other processes can start
3126 ** reading the database file again, make sure that the
3127 ** transaction counter was updated if any part of the database
3128 ** file changed. If the transaction counter is not updated,
3129 ** other connections to the same file might not realize that
3130 ** the file has changed and hence might not know to flush their
3131 ** cache. The use of a stale cache can lead to database corruption.
3132 */
3133 assert( pFile->inNormalWrite==0
3134 || pFile->dbUpdate==0
3135 || pFile->transCntrChng==1 );
3136 pFile->inNormalWrite = 0;
3137#endif
aswiftaebf4132008-11-21 00:10:35 +00003138
drh308c2a52010-05-14 11:30:18 +00003139 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003140 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003141 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003142 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003143 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003144 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3145 } else {
3146 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003147 }
3148 }
drh308c2a52010-05-14 11:30:18 +00003149 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003150 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003151 }
drh308c2a52010-05-14 11:30:18 +00003152 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003153 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3154 if( !rc ){
3155 context->reserved = 0;
3156 }
aswiftaebf4132008-11-21 00:10:35 +00003157 }
drh8af6c222010-05-14 12:43:01 +00003158 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3159 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003160 }
aswiftaebf4132008-11-21 00:10:35 +00003161 }
drh308c2a52010-05-14 11:30:18 +00003162 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003163
drh7ed97b92010-01-20 13:07:21 +00003164 /* Decrement the shared lock counter. Release the lock using an
3165 ** OS call only when all threads in this same process have released
3166 ** the lock.
3167 */
drh8af6c222010-05-14 12:43:01 +00003168 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3169 pInode->nShared--;
3170 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003171 SimulateIOErrorBenign(1);
3172 SimulateIOError( h=(-1) )
3173 SimulateIOErrorBenign(0);
3174 if( !skipShared ){
3175 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3176 }
3177 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003178 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003179 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003180 }
3181 }
3182 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003183 pInode->nLock--;
3184 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00003185 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003186 }
drhbfe66312006-10-03 17:40:40 +00003187 }
drh7ed97b92010-01-20 13:07:21 +00003188
drhda6dc242018-07-23 21:10:37 +00003189 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00003190 if( rc==SQLITE_OK ){
3191 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00003192 }
drhbfe66312006-10-03 17:40:40 +00003193 return rc;
3194}
3195
3196/*
drh339eb0b2008-03-07 15:34:11 +00003197** Close a file & cleanup AFP specific locking context
3198*/
danielk1977e339d652008-06-28 11:23:00 +00003199static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003200 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003201 unixFile *pFile = (unixFile*)id;
3202 assert( id!=0 );
3203 afpUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00003204 assert( unixFileMutexNotheld(pFile) );
drha8de1e12015-11-30 00:05:39 +00003205 unixEnterMutex();
drhef52b362018-08-13 22:50:34 +00003206 if( pFile->pInode ){
3207 unixInodeInfo *pInode = pFile->pInode;
3208 sqlite3_mutex_enter(pInode->pLockMutex);
drhcb4e4b02018-09-06 19:36:29 +00003209 if( pInode->nLock ){
drhef52b362018-08-13 22:50:34 +00003210 /* If there are outstanding locks, do not actually close the file just
3211 ** yet because that would clear those locks. Instead, add the file
3212 ** descriptor to pInode->aPending. It will be automatically closed when
3213 ** the last lock is cleared.
3214 */
3215 setPendingFd(pFile);
3216 }
3217 sqlite3_mutex_leave(pInode->pLockMutex);
danielk1977e339d652008-06-28 11:23:00 +00003218 }
drha8de1e12015-11-30 00:05:39 +00003219 releaseInodeInfo(pFile);
3220 sqlite3_free(pFile->lockingContext);
3221 rc = closeUnixFile(id);
3222 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003223 return rc;
drhbfe66312006-10-03 17:40:40 +00003224}
3225
drhd2cb50b2009-01-09 21:41:17 +00003226#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003227/*
3228** The code above is the AFP lock implementation. The code is specific
3229** to MacOSX and does not work on other unix platforms. No alternative
3230** is available. If you don't compile for a mac, then the "unix-afp"
3231** VFS is not available.
3232**
3233********************* End of the AFP lock implementation **********************
3234******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003235
drh7ed97b92010-01-20 13:07:21 +00003236/******************************************************************************
3237*************************** Begin NFS Locking ********************************/
3238
3239#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3240/*
drh308c2a52010-05-14 11:30:18 +00003241 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003242 ** must be either NO_LOCK or SHARED_LOCK.
3243 **
3244 ** If the locking level of the file descriptor is already at or below
3245 ** the requested locking level, this routine is a no-op.
3246 */
drh308c2a52010-05-14 11:30:18 +00003247static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003248 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003249}
3250
3251#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3252/*
3253** The code above is the NFS lock implementation. The code is specific
3254** to MacOSX and does not work on other unix platforms. No alternative
3255** is available.
3256**
3257********************* End of the NFS lock implementation **********************
3258******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003259
3260/******************************************************************************
3261**************** Non-locking sqlite3_file methods *****************************
3262**
3263** The next division contains implementations for all methods of the
3264** sqlite3_file object other than the locking methods. The locking
3265** methods were defined in divisions above (one locking method per
3266** division). Those methods that are common to all locking modes
3267** are gather together into this division.
3268*/
drhbfe66312006-10-03 17:40:40 +00003269
3270/*
drh734c9862008-11-28 15:37:20 +00003271** Seek to the offset passed as the second argument, then read cnt
3272** bytes into pBuf. Return the number of bytes actually read.
3273**
3274** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3275** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3276** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003277** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003278** See tickets #2741 and #2681.
3279**
3280** To avoid stomping the errno value on a failed read the lastErrno value
3281** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003282*/
drh734c9862008-11-28 15:37:20 +00003283static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3284 int got;
drh58024642011-11-07 18:16:00 +00003285 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003286#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3287 i64 newOffset;
3288#endif
drh734c9862008-11-28 15:37:20 +00003289 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003290 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003291 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003292 do{
drh734c9862008-11-28 15:37:20 +00003293#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003294 got = osPread(id->h, pBuf, cnt, offset);
3295 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003296#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003297 got = osPread64(id->h, pBuf, cnt, offset);
3298 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003299#else
drha46cadc2016-03-04 03:02:06 +00003300 newOffset = lseek(id->h, offset, SEEK_SET);
3301 SimulateIOError( newOffset = -1 );
3302 if( newOffset<0 ){
3303 storeLastErrno((unixFile*)id, errno);
3304 return -1;
3305 }
3306 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003307#endif
drh58024642011-11-07 18:16:00 +00003308 if( got==cnt ) break;
3309 if( got<0 ){
3310 if( errno==EINTR ){ got = 1; continue; }
3311 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003312 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003313 break;
3314 }else if( got>0 ){
3315 cnt -= got;
3316 offset += got;
3317 prior += got;
3318 pBuf = (void*)(got + (char*)pBuf);
3319 }
3320 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003321 TIMER_END;
drh58024642011-11-07 18:16:00 +00003322 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3323 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3324 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003325}
3326
3327/*
drh734c9862008-11-28 15:37:20 +00003328** Read data from a file into a buffer. Return SQLITE_OK if all
3329** bytes were read successfully and SQLITE_IOERR if anything goes
3330** wrong.
drh339eb0b2008-03-07 15:34:11 +00003331*/
drh734c9862008-11-28 15:37:20 +00003332static int unixRead(
3333 sqlite3_file *id,
3334 void *pBuf,
3335 int amt,
3336 sqlite3_int64 offset
3337){
dan08da86a2009-08-21 17:18:03 +00003338 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003339 int got;
3340 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003341 assert( offset>=0 );
3342 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003343
drh067b92b2020-06-19 15:24:12 +00003344 /* If this is a database file (not a journal, super-journal or temp
dan08da86a2009-08-21 17:18:03 +00003345 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003346#if 0
drhc68886b2017-08-18 16:09:52 +00003347 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003348 || offset>=PENDING_BYTE+512
3349 || offset+amt<=PENDING_BYTE
3350 );
dan7c246102010-04-12 19:00:29 +00003351#endif
drh08c6d442009-02-09 17:34:07 +00003352
drh9b4c59f2013-04-15 17:03:42 +00003353#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003354 /* Deal with as much of this read request as possible by transfering
3355 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003356 if( offset<pFile->mmapSize ){
3357 if( offset+amt <= pFile->mmapSize ){
3358 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3359 return SQLITE_OK;
3360 }else{
3361 int nCopy = pFile->mmapSize - offset;
3362 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3363 pBuf = &((u8 *)pBuf)[nCopy];
3364 amt -= nCopy;
3365 offset += nCopy;
3366 }
3367 }
drh6e0b6d52013-04-09 16:19:20 +00003368#endif
danf23da962013-03-23 21:00:41 +00003369
dan08da86a2009-08-21 17:18:03 +00003370 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003371 if( got==amt ){
3372 return SQLITE_OK;
3373 }else if( got<0 ){
3374 /* lastErrno set by seekAndRead */
3375 return SQLITE_IOERR_READ;
3376 }else{
drh4bf66fd2015-02-19 02:43:02 +00003377 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003378 /* Unread parts of the buffer must be zero-filled */
3379 memset(&((char*)pBuf)[got], 0, amt-got);
3380 return SQLITE_IOERR_SHORT_READ;
3381 }
3382}
3383
3384/*
dan47a2b4a2013-04-26 16:09:29 +00003385** Attempt to seek the file-descriptor passed as the first argument to
3386** absolute offset iOff, then attempt to write nBuf bytes of data from
3387** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3388** return the actual number of bytes written (which may be less than
3389** nBuf).
3390*/
3391static int seekAndWriteFd(
3392 int fd, /* File descriptor to write to */
3393 i64 iOff, /* File offset to begin writing at */
3394 const void *pBuf, /* Copy data from this buffer to the file */
3395 int nBuf, /* Size of buffer pBuf in bytes */
3396 int *piErrno /* OUT: Error number if error occurs */
3397){
3398 int rc = 0; /* Value returned by system call */
3399
3400 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003401 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003402 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003403 nBuf &= 0x1ffff;
3404 TIMER_START;
3405
3406#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003407 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003408#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003409 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003410#else
3411 do{
3412 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003413 SimulateIOError( iSeek = -1 );
3414 if( iSeek<0 ){
3415 rc = -1;
3416 break;
dan47a2b4a2013-04-26 16:09:29 +00003417 }
3418 rc = osWrite(fd, pBuf, nBuf);
3419 }while( rc<0 && errno==EINTR );
3420#endif
3421
3422 TIMER_END;
3423 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3424
drhe1818ec2015-12-01 16:21:35 +00003425 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003426 return rc;
3427}
3428
3429
3430/*
drh734c9862008-11-28 15:37:20 +00003431** Seek to the offset in id->offset then read cnt bytes into pBuf.
3432** Return the number of bytes actually read. Update the offset.
3433**
3434** To avoid stomping the errno value on a failed write the lastErrno value
3435** is set before returning.
3436*/
3437static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003438 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003439}
3440
3441
3442/*
3443** Write data from a buffer into a file. Return SQLITE_OK on success
3444** or some other error code on failure.
3445*/
3446static int unixWrite(
3447 sqlite3_file *id,
3448 const void *pBuf,
3449 int amt,
3450 sqlite3_int64 offset
3451){
dan08da86a2009-08-21 17:18:03 +00003452 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003453 int wrote = 0;
3454 assert( id );
3455 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003456
drh067b92b2020-06-19 15:24:12 +00003457 /* If this is a database file (not a journal, super-journal or temp
dan08da86a2009-08-21 17:18:03 +00003458 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003459#if 0
drhc68886b2017-08-18 16:09:52 +00003460 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003461 || offset>=PENDING_BYTE+512
3462 || offset+amt<=PENDING_BYTE
3463 );
dan7c246102010-04-12 19:00:29 +00003464#endif
drh08c6d442009-02-09 17:34:07 +00003465
drhd3d8c042012-05-29 17:02:40 +00003466#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003467 /* If we are doing a normal write to a database file (as opposed to
3468 ** doing a hot-journal rollback or a write to some file other than a
3469 ** normal database file) then record the fact that the database
3470 ** has changed. If the transaction counter is modified, record that
3471 ** fact too.
3472 */
dan08da86a2009-08-21 17:18:03 +00003473 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003474 pFile->dbUpdate = 1; /* The database has been modified */
3475 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003476 int rc;
drh8f941bc2009-01-14 23:03:40 +00003477 char oldCntr[4];
3478 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003479 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003480 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003481 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003482 pFile->transCntrChng = 1; /* The transaction counter has changed */
3483 }
3484 }
3485 }
3486#endif
3487
danfe33e392015-11-17 20:56:06 +00003488#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003489 /* Deal with as much of this write request as possible by transfering
3490 ** data from the memory mapping using memcpy(). */
3491 if( offset<pFile->mmapSize ){
3492 if( offset+amt <= pFile->mmapSize ){
3493 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3494 return SQLITE_OK;
3495 }else{
3496 int nCopy = pFile->mmapSize - offset;
3497 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3498 pBuf = &((u8 *)pBuf)[nCopy];
3499 amt -= nCopy;
3500 offset += nCopy;
3501 }
3502 }
drh6e0b6d52013-04-09 16:19:20 +00003503#endif
drh02bf8b42015-09-01 23:51:53 +00003504
3505 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003506 amt -= wrote;
3507 offset += wrote;
3508 pBuf = &((char*)pBuf)[wrote];
3509 }
3510 SimulateIOError(( wrote=(-1), amt=1 ));
3511 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003512
drh02bf8b42015-09-01 23:51:53 +00003513 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003514 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003515 /* lastErrno set by seekAndWrite */
3516 return SQLITE_IOERR_WRITE;
3517 }else{
drh4bf66fd2015-02-19 02:43:02 +00003518 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003519 return SQLITE_FULL;
3520 }
3521 }
dan6e09d692010-07-27 18:34:15 +00003522
drh734c9862008-11-28 15:37:20 +00003523 return SQLITE_OK;
3524}
3525
3526#ifdef SQLITE_TEST
3527/*
3528** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003529** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003530*/
3531int sqlite3_sync_count = 0;
3532int sqlite3_fullsync_count = 0;
3533#endif
3534
3535/*
drh89240432009-03-25 01:06:01 +00003536** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003537** Others do no. To be safe, we will stick with the (slightly slower)
3538** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003539** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003540*/
drhf7a4a1b2015-01-10 18:02:45 +00003541#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003542# define fdatasync fsync
3543#endif
3544
3545/*
3546** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3547** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3548** only available on Mac OS X. But that could change.
3549*/
3550#ifdef F_FULLFSYNC
3551# define HAVE_FULLFSYNC 1
3552#else
3553# define HAVE_FULLFSYNC 0
3554#endif
3555
3556
3557/*
3558** The fsync() system call does not work as advertised on many
3559** unix systems. The following procedure is an attempt to make
3560** it work better.
3561**
3562** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3563** for testing when we want to run through the test suite quickly.
3564** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3565** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3566** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003567**
3568** SQLite sets the dataOnly flag if the size of the file is unchanged.
3569** The idea behind dataOnly is that it should only write the file content
3570** to disk, not the inode. We only set dataOnly if the file size is
3571** unchanged since the file size is part of the inode. However,
3572** Ted Ts'o tells us that fdatasync() will also write the inode if the
3573** file size has changed. The only real difference between fdatasync()
3574** and fsync(), Ted tells us, is that fdatasync() will not flush the
3575** inode if the mtime or owner or other inode attributes have changed.
3576** We only care about the file size, not the other file attributes, so
3577** as far as SQLite is concerned, an fdatasync() is always adequate.
3578** So, we always use fdatasync() if it is available, regardless of
3579** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003580*/
3581static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003582 int rc;
drh734c9862008-11-28 15:37:20 +00003583
3584 /* The following "ifdef/elif/else/" block has the same structure as
3585 ** the one below. It is replicated here solely to avoid cluttering
3586 ** up the real code with the UNUSED_PARAMETER() macros.
3587 */
3588#ifdef SQLITE_NO_SYNC
3589 UNUSED_PARAMETER(fd);
3590 UNUSED_PARAMETER(fullSync);
3591 UNUSED_PARAMETER(dataOnly);
3592#elif HAVE_FULLFSYNC
3593 UNUSED_PARAMETER(dataOnly);
3594#else
3595 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003596 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003597#endif
3598
3599 /* Record the number of times that we do a normal fsync() and
3600 ** FULLSYNC. This is used during testing to verify that this procedure
3601 ** gets called with the correct arguments.
3602 */
3603#ifdef SQLITE_TEST
3604 if( fullSync ) sqlite3_fullsync_count++;
3605 sqlite3_sync_count++;
3606#endif
3607
3608 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003609 ** no-op. But go ahead and call fstat() to validate the file
3610 ** descriptor as we need a method to provoke a failure during
3611 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003612 */
3613#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003614 {
3615 struct stat buf;
3616 rc = osFstat(fd, &buf);
3617 }
drh734c9862008-11-28 15:37:20 +00003618#elif HAVE_FULLFSYNC
3619 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003620 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003621 }else{
3622 rc = 1;
3623 }
3624 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003625 ** It shouldn't be possible for fullfsync to fail on the local
3626 ** file system (on OSX), so failure indicates that FULLFSYNC
3627 ** isn't supported for this file system. So, attempt an fsync
3628 ** and (for now) ignore the overhead of a superfluous fcntl call.
3629 ** It'd be better to detect fullfsync support once and avoid
3630 ** the fcntl call every time sync is called.
3631 */
drh734c9862008-11-28 15:37:20 +00003632 if( rc ) rc = fsync(fd);
3633
drh7ed97b92010-01-20 13:07:21 +00003634#elif defined(__APPLE__)
3635 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3636 ** so currently we default to the macro that redefines fdatasync to fsync
3637 */
3638 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003639#else
drh0b647ff2009-03-21 14:41:04 +00003640 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003641#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003642 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003643 rc = fsync(fd);
3644 }
drh0b647ff2009-03-21 14:41:04 +00003645#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003646#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3647
3648 if( OS_VXWORKS && rc!= -1 ){
3649 rc = 0;
3650 }
chw97185482008-11-17 08:05:31 +00003651 return rc;
drhbfe66312006-10-03 17:40:40 +00003652}
3653
drh734c9862008-11-28 15:37:20 +00003654/*
drh0059eae2011-08-08 23:48:40 +00003655** Open a file descriptor to the directory containing file zFilename.
3656** If successful, *pFd is set to the opened file descriptor and
3657** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3658** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3659** value.
3660**
drh90315a22011-08-10 01:52:12 +00003661** The directory file descriptor is used for only one thing - to
3662** fsync() a directory to make sure file creation and deletion events
3663** are flushed to disk. Such fsyncs are not needed on newer
3664** journaling filesystems, but are required on older filesystems.
3665**
3666** This routine can be overridden using the xSetSysCall interface.
3667** The ability to override this routine was added in support of the
3668** chromium sandbox. Opening a directory is a security risk (we are
3669** told) so making it overrideable allows the chromium sandbox to
3670** replace this routine with a harmless no-op. To make this routine
3671** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3672** *pFd set to a negative number.
3673**
drh0059eae2011-08-08 23:48:40 +00003674** If SQLITE_OK is returned, the caller is responsible for closing
3675** the file descriptor *pFd using close().
3676*/
3677static int openDirectory(const char *zFilename, int *pFd){
3678 int ii;
3679 int fd = -1;
3680 char zDirname[MAX_PATHNAME+1];
3681
3682 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003683 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3684 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003685 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003686 }else{
3687 if( zDirname[0]!='/' ) zDirname[0] = '.';
3688 zDirname[1] = 0;
3689 }
drh3b9f1542020-04-20 17:35:32 +00003690 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drhdc278512015-12-07 18:18:33 +00003691 if( fd>=0 ){
3692 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003693 }
3694 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003695 if( fd>=0 ) return SQLITE_OK;
3696 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003697}
3698
3699/*
drh734c9862008-11-28 15:37:20 +00003700** Make sure all writes to a particular file are committed to disk.
3701**
3702** If dataOnly==0 then both the file itself and its metadata (file
3703** size, access time, etc) are synced. If dataOnly!=0 then only the
3704** file data is synced.
3705**
3706** Under Unix, also make sure that the directory entry for the file
3707** has been created by fsync-ing the directory that contains the file.
3708** If we do not do this and we encounter a power failure, the directory
3709** entry for the journal might not exist after we reboot. The next
3710** SQLite to access the file will not know that the journal exists (because
3711** the directory entry for the journal was never created) and the transaction
3712** will not roll back - possibly leading to database corruption.
3713*/
3714static int unixSync(sqlite3_file *id, int flags){
3715 int rc;
3716 unixFile *pFile = (unixFile*)id;
3717
3718 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3719 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3720
3721 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3722 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3723 || (flags&0x0F)==SQLITE_SYNC_FULL
3724 );
3725
3726 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3727 ** line is to test that doing so does not cause any problems.
3728 */
3729 SimulateDiskfullError( return SQLITE_FULL );
3730
3731 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003732 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003733 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3734 SimulateIOError( rc=1 );
3735 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003736 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003737 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003738 }
drh0059eae2011-08-08 23:48:40 +00003739
3740 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003741 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003742 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003743 */
3744 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3745 int dirfd;
3746 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003747 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003748 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003749 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003750 full_fsync(dirfd, 0, 0);
3751 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003752 }else{
3753 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003754 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003755 }
drh0059eae2011-08-08 23:48:40 +00003756 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003757 }
3758 return rc;
3759}
3760
3761/*
3762** Truncate an open file to a specified size
3763*/
3764static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003765 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003766 int rc;
dan6e09d692010-07-27 18:34:15 +00003767 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003768 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003769
3770 /* If the user has configured a chunk-size for this file, truncate the
3771 ** file so that it consists of an integer number of chunks (i.e. the
3772 ** actual file size after the operation may be larger than the requested
3773 ** size).
3774 */
drhb8af4b72012-04-05 20:04:39 +00003775 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003776 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3777 }
3778
dan2ee53412014-09-06 16:49:40 +00003779 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003780 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003781 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003782 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003783 }else{
drhd3d8c042012-05-29 17:02:40 +00003784#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003785 /* If we are doing a normal write to a database file (as opposed to
3786 ** doing a hot-journal rollback or a write to some file other than a
3787 ** normal database file) and we truncate the file to zero length,
3788 ** that effectively updates the change counter. This might happen
3789 ** when restoring a database using the backup API from a zero-length
3790 ** source.
3791 */
dan6e09d692010-07-27 18:34:15 +00003792 if( pFile->inNormalWrite && nByte==0 ){
3793 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003794 }
danf23da962013-03-23 21:00:41 +00003795#endif
danc0003312013-03-22 17:46:11 +00003796
mistachkine98844f2013-08-24 00:59:24 +00003797#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003798 /* If the file was just truncated to a size smaller than the currently
3799 ** mapped region, reduce the effective mapping size as well. SQLite will
3800 ** use read() and write() to access data beyond this point from now on.
3801 */
3802 if( nByte<pFile->mmapSize ){
3803 pFile->mmapSize = nByte;
3804 }
mistachkine98844f2013-08-24 00:59:24 +00003805#endif
drh3313b142009-11-06 04:13:18 +00003806
drh734c9862008-11-28 15:37:20 +00003807 return SQLITE_OK;
3808 }
3809}
3810
3811/*
3812** Determine the current size of a file in bytes
3813*/
3814static int unixFileSize(sqlite3_file *id, i64 *pSize){
3815 int rc;
3816 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003817 assert( id );
3818 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003819 SimulateIOError( rc=1 );
3820 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003821 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003822 return SQLITE_IOERR_FSTAT;
3823 }
3824 *pSize = buf.st_size;
3825
drh8af6c222010-05-14 12:43:01 +00003826 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003827 ** writes a single byte into that file in order to work around a bug
3828 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3829 ** layers, we need to report this file size as zero even though it is
3830 ** really 1. Ticket #3260.
3831 */
3832 if( *pSize==1 ) *pSize = 0;
3833
3834
3835 return SQLITE_OK;
3836}
3837
drhd2cb50b2009-01-09 21:41:17 +00003838#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003839/*
3840** Handler for proxy-locking file-control verbs. Defined below in the
3841** proxying locking division.
3842*/
3843static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003844#endif
drh715ff302008-12-03 22:32:44 +00003845
dan502019c2010-07-28 14:26:17 +00003846/*
3847** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003848** file-control operation. Enlarge the database to nBytes in size
3849** (rounded up to the next chunk-size). If the database is already
3850** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003851*/
3852static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003853 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003854 i64 nSize; /* Required file size */
3855 struct stat buf; /* Used to hold return values of fstat() */
3856
drh4bf66fd2015-02-19 02:43:02 +00003857 if( osFstat(pFile->h, &buf) ){
3858 return SQLITE_IOERR_FSTAT;
3859 }
dan502019c2010-07-28 14:26:17 +00003860
3861 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3862 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003863
dan502019c2010-07-28 14:26:17 +00003864#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003865 /* The code below is handling the return value of osFallocate()
3866 ** correctly. posix_fallocate() is defined to "returns zero on success,
3867 ** or an error number on failure". See the manpage for details. */
3868 int err;
drhff812312011-02-23 13:33:46 +00003869 do{
dan661d71a2011-03-30 19:08:03 +00003870 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3871 }while( err==EINTR );
drh789df142018-06-02 14:37:39 +00003872 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003873#else
dan592bf7f2014-12-30 19:58:31 +00003874 /* If the OS does not have posix_fallocate(), fake it. Write a
3875 ** single byte to the last byte in each block that falls entirely
3876 ** within the extended region. Then, if required, a single byte
3877 ** at offset (nSize-1), to set the size of the file correctly.
3878 ** This is a similar technique to that used by glibc on systems
3879 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003880 */
3881 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003882 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003883 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003884
drh053378d2015-12-01 22:09:42 +00003885 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003886 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003887 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003888 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3889 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003890 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003891 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003892 }
dan502019c2010-07-28 14:26:17 +00003893#endif
3894 }
3895 }
3896
mistachkine98844f2013-08-24 00:59:24 +00003897#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003898 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003899 int rc;
3900 if( pFile->szChunk<=0 ){
3901 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003902 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003903 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3904 }
3905 }
3906
3907 rc = unixMapfile(pFile, nByte);
3908 return rc;
3909 }
mistachkine98844f2013-08-24 00:59:24 +00003910#endif
danf23da962013-03-23 21:00:41 +00003911
dan502019c2010-07-28 14:26:17 +00003912 return SQLITE_OK;
3913}
danielk1977ad94b582007-08-20 06:44:22 +00003914
danielk1977e3026632004-06-22 11:29:02 +00003915/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003916** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003917** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3918**
3919** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3920*/
3921static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3922 if( *pArg<0 ){
3923 *pArg = (pFile->ctrlFlags & mask)!=0;
3924 }else if( (*pArg)==0 ){
3925 pFile->ctrlFlags &= ~mask;
3926 }else{
3927 pFile->ctrlFlags |= mask;
3928 }
3929}
3930
drh696b33e2012-12-06 19:01:42 +00003931/* Forward declaration */
3932static int unixGetTempname(int nBuf, char *zBuf);
3933
drhf12b3f62011-12-21 14:42:29 +00003934/*
drh9e33c2c2007-08-31 18:34:59 +00003935** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003936*/
drhcc6bb3e2007-08-31 16:11:35 +00003937static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003938 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003939 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003940#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003941 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3942 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003943 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003944 }
3945 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3946 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003947 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003948 }
3949 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3950 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003951 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003952 }
drhd76dba72017-07-22 16:00:34 +00003953#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003954
drh9e33c2c2007-08-31 18:34:59 +00003955 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003956 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003957 return SQLITE_OK;
3958 }
drh4bf66fd2015-02-19 02:43:02 +00003959 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003960 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003961 return SQLITE_OK;
3962 }
dan6e09d692010-07-27 18:34:15 +00003963 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003964 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003965 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003966 }
drh9ff27ec2010-05-19 19:26:05 +00003967 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003968 int rc;
3969 SimulateIOErrorBenign(1);
3970 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3971 SimulateIOErrorBenign(0);
3972 return rc;
drhf0b190d2011-07-26 16:03:07 +00003973 }
3974 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003975 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3976 return SQLITE_OK;
3977 }
drhcb15f352011-12-23 01:04:17 +00003978 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3979 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003980 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003981 }
drhde60fc22011-12-14 17:53:36 +00003982 case SQLITE_FCNTL_VFSNAME: {
3983 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3984 return SQLITE_OK;
3985 }
drh696b33e2012-12-06 19:01:42 +00003986 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003987 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003988 if( zTFile ){
3989 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3990 *(char**)pArg = zTFile;
3991 }
3992 return SQLITE_OK;
3993 }
drhb959a012013-12-07 12:29:22 +00003994 case SQLITE_FCNTL_HAS_MOVED: {
3995 *(int*)pArg = fileHasMoved(pFile);
3996 return SQLITE_OK;
3997 }
drhf0119b22018-03-26 17:40:53 +00003998#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3999 case SQLITE_FCNTL_LOCK_TIMEOUT: {
dan97ccc1b2020-03-27 17:23:17 +00004000 int iOld = pFile->iBusyTimeout;
drhf0119b22018-03-26 17:40:53 +00004001 pFile->iBusyTimeout = *(int*)pArg;
dan97ccc1b2020-03-27 17:23:17 +00004002 *(int*)pArg = iOld;
drhf0119b22018-03-26 17:40:53 +00004003 return SQLITE_OK;
4004 }
4005#endif
mistachkine98844f2013-08-24 00:59:24 +00004006#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00004007 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00004008 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00004009 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00004010 if( newLimit>sqlite3GlobalConfig.mxMmap ){
4011 newLimit = sqlite3GlobalConfig.mxMmap;
4012 }
dan43c1e622017-08-07 18:13:28 +00004013
4014 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00004015 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4016 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00004017 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00004018 newLimit = (newLimit & 0x7FFFFFFF);
4019 }
4020
drh9b4c59f2013-04-15 17:03:42 +00004021 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00004022 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00004023 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00004024 if( pFile->mmapSize>0 ){
4025 unixUnmapfile(pFile);
4026 rc = unixMapfile(pFile, -1);
4027 }
danbcb8a862013-04-08 15:30:41 +00004028 }
drh34e258c2013-05-23 01:40:53 +00004029 return rc;
danb2d3de32013-03-14 18:34:37 +00004030 }
mistachkine98844f2013-08-24 00:59:24 +00004031#endif
drhd3d8c042012-05-29 17:02:40 +00004032#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00004033 /* The pager calls this method to signal that it has done
4034 ** a rollback and that the database is therefore unchanged and
4035 ** it hence it is OK for the transaction change counter to be
4036 ** unchanged.
4037 */
4038 case SQLITE_FCNTL_DB_UNCHANGED: {
4039 ((unixFile*)id)->dbUpdate = 0;
4040 return SQLITE_OK;
4041 }
4042#endif
drhd2cb50b2009-01-09 21:41:17 +00004043#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00004044 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4045 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00004046 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00004047 }
drhd2cb50b2009-01-09 21:41:17 +00004048#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00004049 }
drh0b52b7d2011-01-26 19:46:22 +00004050 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00004051}
4052
4053/*
danefe16972017-07-20 19:49:14 +00004054** If pFd->sectorSize is non-zero when this function is called, it is a
4055** no-op. Otherwise, the values of pFd->sectorSize and
4056** pFd->deviceCharacteristics are set according to the file-system
4057** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00004058**
danefe16972017-07-20 19:49:14 +00004059** There are two versions of this function. One for QNX and one for all
4060** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00004061*/
danefe16972017-07-20 19:49:14 +00004062#ifndef __QNXNTO__
4063static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00004064 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00004065 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00004066#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00004067 int res;
dan9d709542017-07-21 21:06:24 +00004068 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00004069
danefe16972017-07-20 19:49:14 +00004070 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00004071 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4072 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00004073 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00004074 }
drhd76dba72017-07-22 16:00:34 +00004075#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00004076
4077 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4078 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4079 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4080 }
4081
4082 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4083 }
4084}
4085#else
drh537dddf2012-10-26 13:46:24 +00004086#include <sys/dcmd_blk.h>
4087#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00004088static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00004089 if( pFile->sectorSize == 0 ){
4090 struct statvfs fsInfo;
4091
4092 /* Set defaults for non-supported filesystems */
4093 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4094 pFile->deviceCharacteristics = 0;
4095 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00004096 return;
drh537dddf2012-10-26 13:46:24 +00004097 }
4098
4099 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4100 pFile->sectorSize = fsInfo.f_bsize;
4101 pFile->deviceCharacteristics =
4102 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4103 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4104 ** the write succeeds */
4105 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4106 ** so it is ordered */
4107 0;
4108 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4109 pFile->sectorSize = fsInfo.f_bsize;
4110 pFile->deviceCharacteristics =
4111 /* etfs cluster size writes are atomic */
4112 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4113 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4114 ** the write succeeds */
4115 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4116 ** so it is ordered */
4117 0;
4118 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4119 pFile->sectorSize = fsInfo.f_bsize;
4120 pFile->deviceCharacteristics =
4121 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4122 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4123 ** the write succeeds */
4124 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4125 ** so it is ordered */
4126 0;
4127 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4128 pFile->sectorSize = fsInfo.f_bsize;
4129 pFile->deviceCharacteristics =
4130 /* full bitset of atomics from max sector size and smaller */
4131 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4132 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4133 ** so it is ordered */
4134 0;
4135 }else if( strstr(fsInfo.f_basetype, "dos") ){
4136 pFile->sectorSize = fsInfo.f_bsize;
4137 pFile->deviceCharacteristics =
4138 /* full bitset of atomics from max sector size and smaller */
4139 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4140 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4141 ** so it is ordered */
4142 0;
4143 }else{
4144 pFile->deviceCharacteristics =
4145 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4146 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4147 ** the write succeeds */
4148 0;
4149 }
4150 }
4151 /* Last chance verification. If the sector size isn't a multiple of 512
4152 ** then it isn't valid.*/
4153 if( pFile->sectorSize % 512 != 0 ){
4154 pFile->deviceCharacteristics = 0;
4155 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4156 }
drh537dddf2012-10-26 13:46:24 +00004157}
danefe16972017-07-20 19:49:14 +00004158#endif
4159
4160/*
4161** Return the sector size in bytes of the underlying block device for
4162** the specified file. This is almost always 512 bytes, but may be
4163** larger for some devices.
4164**
4165** SQLite code assumes this function cannot fail. It also assumes that
4166** if two files are created in the same file-system directory (i.e.
4167** a database and its journal file) that the sector size will be the
4168** same for both.
4169*/
4170static int unixSectorSize(sqlite3_file *id){
4171 unixFile *pFd = (unixFile*)id;
4172 setDeviceCharacteristics(pFd);
4173 return pFd->sectorSize;
4174}
danielk1977a3d4c882007-03-23 10:08:38 +00004175
danielk197790949c22007-08-17 16:50:38 +00004176/*
drhf12b3f62011-12-21 14:42:29 +00004177** Return the device characteristics for the file.
4178**
drhcb15f352011-12-23 01:04:17 +00004179** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004180** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004181** file system does not always provide powersafe overwrites. (In other
4182** words, after a power-loss event, parts of the file that were never
4183** written might end up being altered.) However, non-PSOW behavior is very,
4184** very rare. And asserting PSOW makes a large reduction in the amount
4185** of required I/O for journaling, since a lot of padding is eliminated.
4186** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4187** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004188*/
drhf12b3f62011-12-21 14:42:29 +00004189static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004190 unixFile *pFd = (unixFile*)id;
4191 setDeviceCharacteristics(pFd);
4192 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004193}
4194
dan702eec12014-06-23 10:04:58 +00004195#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004196
dan702eec12014-06-23 10:04:58 +00004197/*
4198** Return the system page size.
4199**
4200** This function should not be called directly by other code in this file.
4201** Instead, it should be called via macro osGetpagesize().
4202*/
4203static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004204#if OS_VXWORKS
4205 return 1024;
4206#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004207 return getpagesize();
4208#else
4209 return (int)sysconf(_SC_PAGESIZE);
4210#endif
4211}
4212
4213#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4214
4215#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004216
4217/*
drhd91c68f2010-05-14 14:52:25 +00004218** Object used to represent an shared memory buffer.
4219**
4220** When multiple threads all reference the same wal-index, each thread
4221** has its own unixShm object, but they all point to a single instance
4222** of this unixShmNode object. In other words, each wal-index is opened
4223** only once per process.
4224**
4225** Each unixShmNode object is connected to a single unixInodeInfo object.
4226** We could coalesce this object into unixInodeInfo, but that would mean
4227** every open file that does not use shared memory (in other words, most
4228** open files) would have to carry around this extra information. So
4229** the unixInodeInfo object contains a pointer to this unixShmNode object
4230** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004231**
4232** unixMutexHeld() must be true when creating or destroying
4233** this object or while reading or writing the following fields:
4234**
4235** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004236**
4237** The following fields are read-only after the object is created:
4238**
drh8820c8d2018-10-02 19:58:08 +00004239** hShm
drhd9e5c4f2010-05-12 18:01:39 +00004240** zFilename
4241**
drh8820c8d2018-10-02 19:58:08 +00004242** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004243** unixMutexHeld() is true when reading or writing any other field
4244** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004245*/
drhd91c68f2010-05-14 14:52:25 +00004246struct unixShmNode {
4247 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drh24efa542018-10-02 19:36:40 +00004248 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004249 char *zFilename; /* Name of the mmapped file */
drh8820c8d2018-10-02 19:58:08 +00004250 int hShm; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004251 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004252 u16 nRegion; /* Size of array apRegion */
4253 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004254 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004255 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004256 int nRef; /* Number of unixShm objects pointing to this */
4257 unixShm *pFirst; /* All unixShm objects pointing to this */
dan8337da62020-08-28 19:27:15 +00004258 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
drhd9e5c4f2010-05-12 18:01:39 +00004259#ifdef SQLITE_DEBUG
4260 u8 exclMask; /* Mask of exclusive locks held */
4261 u8 sharedMask; /* Mask of shared locks held */
4262 u8 nextShmId; /* Next available unixShm.id value */
4263#endif
4264};
4265
4266/*
drhd9e5c4f2010-05-12 18:01:39 +00004267** Structure used internally by this VFS to record the state of an
4268** open shared memory connection.
4269**
drhd91c68f2010-05-14 14:52:25 +00004270** The following fields are initialized when this object is created and
4271** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004272**
drh24efa542018-10-02 19:36:40 +00004273** unixShm.pShmNode
drhd91c68f2010-05-14 14:52:25 +00004274** unixShm.id
4275**
drh24efa542018-10-02 19:36:40 +00004276** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4277** be held while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004278*/
4279struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004280 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4281 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drh24efa542018-10-02 19:36:40 +00004282 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
drhfd532312011-08-31 18:35:34 +00004283 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004284 u16 sharedMask; /* Mask of shared locks held */
4285 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004286};
4287
4288/*
drhd9e5c4f2010-05-12 18:01:39 +00004289** Constants used for locking
4290*/
drhbd9676c2010-06-23 17:58:38 +00004291#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004292#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004293
drhd9e5c4f2010-05-12 18:01:39 +00004294/*
drh73b64e42010-05-30 19:55:15 +00004295** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004296**
4297** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4298** otherwise.
4299*/
4300static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004301 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004302 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004303 int ofst, /* First byte of the locking range */
4304 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004305){
drhbbf76ee2015-03-10 20:22:35 +00004306 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4307 struct flock f; /* The posix advisory locking structure */
4308 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004309
drhd91c68f2010-05-14 14:52:25 +00004310 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004311 pShmNode = pFile->pInode->pShmNode;
drh24efa542018-10-02 19:36:40 +00004312 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
drh9b7e8e12018-10-02 20:16:41 +00004313 assert( pShmNode->nRef>0 || unixMutexHeld() );
drhd9e5c4f2010-05-12 18:01:39 +00004314
dan9181ae92017-10-26 17:05:22 +00004315 /* Shared locks never span more than one byte */
4316 assert( n==1 || lockType!=F_RDLCK );
4317
4318 /* Locks are within range */
4319 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4320
drh8820c8d2018-10-02 19:58:08 +00004321 if( pShmNode->hShm>=0 ){
dan7bb8b8a2020-05-06 20:27:18 +00004322 int res;
drh3cb93392011-03-12 18:10:44 +00004323 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004324 f.l_type = lockType;
4325 f.l_whence = SEEK_SET;
4326 f.l_start = ofst;
4327 f.l_len = n;
dan7bb8b8a2020-05-06 20:27:18 +00004328 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
4329 if( res==-1 ){
dan7a623e12020-05-06 20:45:11 +00004330#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
dan7bb8b8a2020-05-06 20:27:18 +00004331 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
dan7a623e12020-05-06 20:45:11 +00004332#else
4333 rc = SQLITE_BUSY;
4334#endif
dan7bb8b8a2020-05-06 20:27:18 +00004335 }
drh3cb93392011-03-12 18:10:44 +00004336 }
drhd9e5c4f2010-05-12 18:01:39 +00004337
4338 /* Update the global lock state and do debug tracing */
4339#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004340 { u16 mask;
4341 OSTRACE(("SHM-LOCK "));
4342 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4343 if( rc==SQLITE_OK ){
4344 if( lockType==F_UNLCK ){
4345 OSTRACE(("unlock %d ok", ofst));
4346 pShmNode->exclMask &= ~mask;
4347 pShmNode->sharedMask &= ~mask;
4348 }else if( lockType==F_RDLCK ){
4349 OSTRACE(("read-lock %d ok", ofst));
4350 pShmNode->exclMask &= ~mask;
4351 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004352 }else{
dan9181ae92017-10-26 17:05:22 +00004353 assert( lockType==F_WRLCK );
4354 OSTRACE(("write-lock %d ok", ofst));
4355 pShmNode->exclMask |= mask;
4356 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004357 }
dan9181ae92017-10-26 17:05:22 +00004358 }else{
4359 if( lockType==F_UNLCK ){
4360 OSTRACE(("unlock %d failed", ofst));
4361 }else if( lockType==F_RDLCK ){
4362 OSTRACE(("read-lock failed"));
4363 }else{
4364 assert( lockType==F_WRLCK );
4365 OSTRACE(("write-lock %d failed", ofst));
4366 }
4367 }
4368 OSTRACE((" - afterwards %03x,%03x\n",
4369 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004370 }
drhd9e5c4f2010-05-12 18:01:39 +00004371#endif
4372
4373 return rc;
4374}
4375
dan781e34c2014-03-20 08:59:47 +00004376/*
dan781e34c2014-03-20 08:59:47 +00004377** Return the minimum number of 32KB shm regions that should be mapped at
4378** a time, assuming that each mapping must be an integer multiple of the
4379** current system page-size.
4380**
4381** Usually, this is 1. The exception seems to be systems that are configured
4382** to use 64KB pages - in this case each mapping must cover at least two
4383** shm regions.
4384*/
4385static int unixShmRegionPerMap(void){
4386 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004387 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004388 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4389 if( pgsz<shmsz ) return 1;
4390 return pgsz/shmsz;
4391}
drhd9e5c4f2010-05-12 18:01:39 +00004392
4393/*
drhd91c68f2010-05-14 14:52:25 +00004394** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004395**
4396** This is not a VFS shared-memory method; it is a utility function called
4397** by VFS shared-memory methods.
4398*/
drhd91c68f2010-05-14 14:52:25 +00004399static void unixShmPurge(unixFile *pFd){
4400 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004401 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004402 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004403 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004404 int i;
drhd91c68f2010-05-14 14:52:25 +00004405 assert( p->pInode==pFd->pInode );
drh24efa542018-10-02 19:36:40 +00004406 sqlite3_mutex_free(p->pShmMutex);
dan781e34c2014-03-20 08:59:47 +00004407 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh8820c8d2018-10-02 19:58:08 +00004408 if( p->hShm>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004409 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004410 }else{
4411 sqlite3_free(p->apRegion[i]);
4412 }
dan13a3cb82010-06-11 19:04:21 +00004413 }
dan18801912010-06-14 14:07:50 +00004414 sqlite3_free(p->apRegion);
drh8820c8d2018-10-02 19:58:08 +00004415 if( p->hShm>=0 ){
4416 robust_close(pFd, p->hShm, __LINE__);
4417 p->hShm = -1;
drh0e9365c2011-03-02 02:08:13 +00004418 }
drhd91c68f2010-05-14 14:52:25 +00004419 p->pInode->pShmNode = 0;
4420 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004421 }
4422}
4423
4424/*
dan92c02da2017-11-01 20:59:28 +00004425** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4426** take it now. Return SQLITE_OK if successful, or an SQLite error
4427** code otherwise.
4428**
4429** If the DMS cannot be locked because this is a readonly_shm=1
4430** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004431** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004432*/
4433static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4434 struct flock lock;
4435 int rc = SQLITE_OK;
4436
4437 /* Use F_GETLK to determine the locks other processes are holding
4438 ** on the DMS byte. If it indicates that another process is holding
4439 ** a SHARED lock, then this process may also take a SHARED lock
4440 ** and proceed with opening the *-shm file.
4441 **
4442 ** Or, if no other process is holding any lock, then this process
4443 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4444 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4445 ** downgrade to a SHARED lock on the DMS byte.
4446 **
4447 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4448 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4449 ** version of this code attempted the SHARED lock at this point. But
4450 ** this introduced a subtle race condition: if the process holding
4451 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4452 ** process might open and use the *-shm file without truncating it.
4453 ** And if the *-shm file has been corrupted by a power failure or
4454 ** system crash, the database itself may also become corrupt. */
4455 lock.l_whence = SEEK_SET;
4456 lock.l_start = UNIX_SHM_DMS;
4457 lock.l_len = 1;
4458 lock.l_type = F_WRLCK;
drh8820c8d2018-10-02 19:58:08 +00004459 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
dan92c02da2017-11-01 20:59:28 +00004460 rc = SQLITE_IOERR_LOCK;
4461 }else if( lock.l_type==F_UNLCK ){
4462 if( pShmNode->isReadonly ){
4463 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004464 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004465 }else{
4466 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
drhf7f2a822018-10-11 13:51:48 +00004467 /* The first connection to attach must truncate the -shm file. We
4468 ** truncate to 3 bytes (an arbitrary small number, less than the
4469 ** -shm header size) rather than 0 as a system debugging aid, to
4470 ** help detect if a -shm file truncation is legitimate or is the work
4471 ** or a rogue process. */
4472 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
dan92c02da2017-11-01 20:59:28 +00004473 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4474 }
4475 }
4476 }else if( lock.l_type==F_WRLCK ){
4477 rc = SQLITE_BUSY;
4478 }
4479
4480 if( rc==SQLITE_OK ){
4481 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4482 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4483 }
4484 return rc;
4485}
4486
4487/*
danda9fe0c2010-07-13 18:44:03 +00004488** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004489** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004490**
drh7234c6d2010-06-19 15:10:09 +00004491** The file used to implement shared-memory is in the same directory
4492** as the open database file and has the same name as the open database
4493** file with the "-shm" suffix added. For example, if the database file
4494** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004495** for shared memory will be called "/home/user1/config.db-shm".
4496**
4497** Another approach to is to use files in /dev/shm or /dev/tmp or an
4498** some other tmpfs mount. But if a file in a different directory
4499** from the database file is used, then differing access permissions
4500** or a chroot() might cause two different processes on the same
4501** database to end up using different files for shared memory -
4502** meaning that their memory would not really be shared - resulting
4503** in database corruption. Nevertheless, this tmpfs file usage
4504** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4505** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4506** option results in an incompatible build of SQLite; builds of SQLite
4507** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4508** same database file at the same time, database corruption will likely
4509** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4510** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004511**
4512** When opening a new shared-memory file, if no other instances of that
4513** file are currently open, in this process or in other processes, then
4514** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004515**
4516** If the original database file (pDbFd) is using the "unix-excl" VFS
4517** that means that an exclusive lock is held on the database file and
4518** that no other processes are able to read or write the database. In
4519** that case, we do not really need shared memory. No shared memory
4520** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004521*/
danda9fe0c2010-07-13 18:44:03 +00004522static int unixOpenSharedMemory(unixFile *pDbFd){
4523 struct unixShm *p = 0; /* The connection to be opened */
4524 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004525 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004526 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004527 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004528 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004529
danda9fe0c2010-07-13 18:44:03 +00004530 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004531 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004532 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004533 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004534 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004535
danda9fe0c2010-07-13 18:44:03 +00004536 /* Check to see if a unixShmNode object already exists. Reuse an existing
4537 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004538 */
drh095908e2018-08-13 20:46:18 +00004539 assert( unixFileMutexNotheld(pDbFd) );
drhd9e5c4f2010-05-12 18:01:39 +00004540 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004541 pInode = pDbFd->pInode;
4542 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004543 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004544 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004545#ifndef SQLITE_SHM_DIRECTORY
4546 const char *zBasePath = pDbFd->zPath;
4547#endif
danddb0ac42010-07-14 14:48:58 +00004548
4549 /* Call fstat() to figure out the permissions on the database file. If
4550 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004551 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004552 */
drhf3b1ed02015-12-02 13:11:03 +00004553 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004554 rc = SQLITE_IOERR_FSTAT;
4555 goto shm_open_err;
4556 }
4557
drha4ced192010-07-15 18:32:40 +00004558#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004559 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004560#else
drh4bf66fd2015-02-19 02:43:02 +00004561 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004562#endif
drhf3cdcdc2015-04-29 16:50:28 +00004563 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004564 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004565 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004566 goto shm_open_err;
4567 }
drh9cb5a0d2012-01-05 21:19:54 +00004568 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004569 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004570#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004571 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004572 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4573 (u32)sStat.st_ino, (u32)sStat.st_dev);
4574#else
danf12ba662017-11-07 15:43:52 +00004575 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4576 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004577#endif
drh8820c8d2018-10-02 19:58:08 +00004578 pShmNode->hShm = -1;
drhd91c68f2010-05-14 14:52:25 +00004579 pDbFd->pInode->pShmNode = pShmNode;
4580 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004581 if( sqlite3GlobalConfig.bCoreMutex ){
drh24efa542018-10-02 19:36:40 +00004582 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4583 if( pShmNode->pShmMutex==0 ){
drh97a7e5e2016-04-26 18:58:54 +00004584 rc = SQLITE_NOMEM_BKPT;
4585 goto shm_open_err;
4586 }
drhd91c68f2010-05-14 14:52:25 +00004587 }
drhd9e5c4f2010-05-12 18:01:39 +00004588
drh3cb93392011-03-12 18:10:44 +00004589 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004590 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drhc398c652019-11-22 00:42:01 +00004591 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
4592 (sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004593 }
drh8820c8d2018-10-02 19:58:08 +00004594 if( pShmNode->hShm<0 ){
drhc398c652019-11-22 00:42:01 +00004595 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
4596 (sStat.st_mode&0777));
drh8820c8d2018-10-02 19:58:08 +00004597 if( pShmNode->hShm<0 ){
danf12ba662017-11-07 15:43:52 +00004598 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4599 goto shm_open_err;
4600 }
4601 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004602 }
drhac7c3ac2012-02-11 19:23:48 +00004603
4604 /* If this process is running as root, make sure that the SHM file
4605 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004606 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004607 */
drh8820c8d2018-10-02 19:58:08 +00004608 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004609
dan92c02da2017-11-01 20:59:28 +00004610 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004611 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004612 }
drhd9e5c4f2010-05-12 18:01:39 +00004613 }
4614
drhd91c68f2010-05-14 14:52:25 +00004615 /* Make the new connection a child of the unixShmNode */
4616 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004617#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004618 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004619#endif
drhd91c68f2010-05-14 14:52:25 +00004620 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004621 pDbFd->pShm = p;
4622 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004623
4624 /* The reference count on pShmNode has already been incremented under
4625 ** the cover of the unixEnterMutex() mutex and the pointer from the
4626 ** new (struct unixShm) object to the pShmNode has been set. All that is
4627 ** left to do is to link the new object into the linked list starting
drh24efa542018-10-02 19:36:40 +00004628 ** at pShmNode->pFirst. This must be done while holding the
4629 ** pShmNode->pShmMutex.
dan0668f592010-07-20 18:59:00 +00004630 */
drh24efa542018-10-02 19:36:40 +00004631 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan0668f592010-07-20 18:59:00 +00004632 p->pNext = pShmNode->pFirst;
4633 pShmNode->pFirst = p;
drh24efa542018-10-02 19:36:40 +00004634 sqlite3_mutex_leave(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004635 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004636
4637 /* Jump here on any error */
4638shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004639 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004640 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004641 unixLeaveMutex();
4642 return rc;
4643}
4644
4645/*
danda9fe0c2010-07-13 18:44:03 +00004646** This function is called to obtain a pointer to region iRegion of the
4647** shared-memory associated with the database file fd. Shared-memory regions
4648** are numbered starting from zero. Each shared-memory region is szRegion
4649** bytes in size.
4650**
4651** If an error occurs, an error code is returned and *pp is set to NULL.
4652**
4653** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4654** region has not been allocated (by any client, including one running in a
4655** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4656** bExtend is non-zero and the requested shared-memory region has not yet
4657** been allocated, it is allocated by this function.
4658**
4659** If the shared-memory region has already been allocated or is allocated by
4660** this call as described above, then it is mapped into this processes
4661** address space (if it is not already), *pp is set to point to the mapped
4662** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004663*/
danda9fe0c2010-07-13 18:44:03 +00004664static int unixShmMap(
4665 sqlite3_file *fd, /* Handle open on database file */
4666 int iRegion, /* Region to retrieve */
4667 int szRegion, /* Size of regions */
4668 int bExtend, /* True to extend file if necessary */
4669 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004670){
danda9fe0c2010-07-13 18:44:03 +00004671 unixFile *pDbFd = (unixFile*)fd;
4672 unixShm *p;
4673 unixShmNode *pShmNode;
4674 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004675 int nShmPerMap = unixShmRegionPerMap();
4676 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004677
danda9fe0c2010-07-13 18:44:03 +00004678 /* If the shared-memory file has not yet been opened, open it now. */
4679 if( pDbFd->pShm==0 ){
4680 rc = unixOpenSharedMemory(pDbFd);
4681 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004682 }
drhd9e5c4f2010-05-12 18:01:39 +00004683
danda9fe0c2010-07-13 18:44:03 +00004684 p = pDbFd->pShm;
4685 pShmNode = p->pShmNode;
drh24efa542018-10-02 19:36:40 +00004686 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004687 if( pShmNode->isUnlocked ){
4688 rc = unixLockSharedMemory(pDbFd, pShmNode);
4689 if( rc!=SQLITE_OK ) goto shmpage_out;
4690 pShmNode->isUnlocked = 0;
4691 }
danda9fe0c2010-07-13 18:44:03 +00004692 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004693 assert( pShmNode->pInode==pDbFd->pInode );
drh8820c8d2018-10-02 19:58:08 +00004694 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4695 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004696
dan781e34c2014-03-20 08:59:47 +00004697 /* Minimum number of regions required to be mapped. */
4698 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4699
4700 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004701 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004702 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004703 struct stat sStat; /* Used by fstat() */
4704
4705 pShmNode->szRegion = szRegion;
4706
drh8820c8d2018-10-02 19:58:08 +00004707 if( pShmNode->hShm>=0 ){
drh3cb93392011-03-12 18:10:44 +00004708 /* The requested region is not mapped into this processes address space.
4709 ** Check to see if it has been allocated (i.e. if the wal-index file is
4710 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004711 */
drh8820c8d2018-10-02 19:58:08 +00004712 if( osFstat(pShmNode->hShm, &sStat) ){
drh3cb93392011-03-12 18:10:44 +00004713 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004714 goto shmpage_out;
4715 }
drh3cb93392011-03-12 18:10:44 +00004716
4717 if( sStat.st_size<nByte ){
4718 /* The requested memory region does not exist. If bExtend is set to
4719 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004720 */
dan47a2b4a2013-04-26 16:09:29 +00004721 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004722 goto shmpage_out;
4723 }
dan47a2b4a2013-04-26 16:09:29 +00004724
4725 /* Alternatively, if bExtend is true, extend the file. Do this by
4726 ** writing a single byte to the end of each (OS) page being
4727 ** allocated or extended. Technically, we need only write to the
4728 ** last page in order to extend the file. But writing to all new
4729 ** pages forces the OS to allocate them immediately, which reduces
4730 ** the chances of SIGBUS while accessing the mapped region later on.
4731 */
4732 else{
4733 static const int pgsz = 4096;
4734 int iPg;
4735
4736 /* Write to the last byte of each newly allocated or extended page */
4737 assert( (nByte % pgsz)==0 );
4738 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004739 int x = 0;
drh8820c8d2018-10-02 19:58:08 +00004740 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004741 const char *zFile = pShmNode->zFilename;
4742 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4743 goto shmpage_out;
4744 }
4745 }
drh3cb93392011-03-12 18:10:44 +00004746 }
4747 }
danda9fe0c2010-07-13 18:44:03 +00004748 }
4749
4750 /* Map the requested memory region into this processes address space. */
4751 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004752 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004753 );
4754 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004755 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004756 goto shmpage_out;
4757 }
4758 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004759 while( pShmNode->nRegion<nReqRegion ){
4760 int nMap = szRegion*nShmPerMap;
4761 int i;
drh3cb93392011-03-12 18:10:44 +00004762 void *pMem;
drh8820c8d2018-10-02 19:58:08 +00004763 if( pShmNode->hShm>=0 ){
dan781e34c2014-03-20 08:59:47 +00004764 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004765 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh8820c8d2018-10-02 19:58:08 +00004766 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004767 );
4768 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004769 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004770 goto shmpage_out;
4771 }
4772 }else{
drhb6c4d592018-10-11 02:39:11 +00004773 pMem = sqlite3_malloc64(nMap);
drh3cb93392011-03-12 18:10:44 +00004774 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004775 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004776 goto shmpage_out;
4777 }
drhb6c4d592018-10-11 02:39:11 +00004778 memset(pMem, 0, nMap);
danda9fe0c2010-07-13 18:44:03 +00004779 }
dan781e34c2014-03-20 08:59:47 +00004780
4781 for(i=0; i<nShmPerMap; i++){
4782 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4783 }
4784 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004785 }
4786 }
4787
4788shmpage_out:
4789 if( pShmNode->nRegion>iRegion ){
4790 *pp = pShmNode->apRegion[iRegion];
4791 }else{
4792 *pp = 0;
4793 }
drh66dfec8b2011-06-01 20:01:49 +00004794 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
drh24efa542018-10-02 19:36:40 +00004795 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004796 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004797}
4798
4799/*
dan8337da62020-08-28 19:27:15 +00004800** Check that the pShmNode->aLock[] array comports with the locking bitmasks
4801** held by each client. Return true if it does, or false otherwise. This
4802** is to be used in an assert(). e.g.
4803**
4804** assert( assertLockingArrayOk(pShmNode) );
4805*/
4806#ifdef SQLITE_DEBUG
4807static int assertLockingArrayOk(unixShmNode *pShmNode){
4808 unixShm *pX;
4809 int aLock[SQLITE_SHM_NLOCK];
4810 assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
4811
4812 memset(aLock, 0, sizeof(aLock));
4813 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4814 int i;
4815 for(i=0; i<SQLITE_SHM_NLOCK; i++){
4816 if( pX->exclMask & (1<<i) ){
4817 assert( aLock[i]==0 );
4818 aLock[i] = -1;
4819 }else if( pX->sharedMask & (1<<i) ){
4820 assert( aLock[i]>=0 );
4821 aLock[i]++;
4822 }
4823 }
4824 }
4825
4826 assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
4827 return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
4828}
4829#endif
4830
4831/*
drhd9e5c4f2010-05-12 18:01:39 +00004832** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004833**
4834** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4835** different here than in posix. In xShmLock(), one can go from unlocked
4836** to shared and back or from unlocked to exclusive and back. But one may
4837** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004838*/
4839static int unixShmLock(
4840 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004841 int ofst, /* First lock to acquire or release */
4842 int n, /* Number of locks to acquire or release */
4843 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004844){
drh73b64e42010-05-30 19:55:15 +00004845 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4846 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
drh73b64e42010-05-30 19:55:15 +00004847 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4848 int rc = SQLITE_OK; /* Result code */
4849 u16 mask; /* Mask of locks to take or release */
dan8337da62020-08-28 19:27:15 +00004850 int *aLock = pShmNode->aLock;
drhd9e5c4f2010-05-12 18:01:39 +00004851
drhd91c68f2010-05-14 14:52:25 +00004852 assert( pShmNode==pDbFd->pInode->pShmNode );
4853 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004854 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004855 assert( n>=1 );
4856 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4857 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4858 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4859 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4860 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh8820c8d2018-10-02 19:58:08 +00004861 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4862 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004863
dan58021b22020-05-05 20:30:07 +00004864 /* Check that, if this to be a blocking lock, no locks that occur later
4865 ** in the following list than the lock being obtained are already held:
dan97ccc1b2020-03-27 17:23:17 +00004866 **
4867 ** 1. Checkpointer lock (ofst==1).
dan58021b22020-05-05 20:30:07 +00004868 ** 2. Write lock (ofst==0).
dan97ccc1b2020-03-27 17:23:17 +00004869 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
dan97ccc1b2020-03-27 17:23:17 +00004870 **
4871 ** In other words, if this is a blocking lock, none of the locks that
4872 ** occur later in the above list than the lock being obtained may be
dand31fcd42020-05-29 11:07:20 +00004873 ** held.
4874 **
4875 ** It is not permitted to block on the RECOVER lock.
4876 */
dan97ccc1b2020-03-27 17:23:17 +00004877#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
dan58021b22020-05-05 20:30:07 +00004878 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
4879 (ofst!=2) /* not RECOVER */
dan58021b22020-05-05 20:30:07 +00004880 && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
4881 && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
4882 && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
4883 ));
dan97ccc1b2020-03-27 17:23:17 +00004884#endif
4885
drhc99597c2010-05-31 01:41:15 +00004886 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004887 assert( n>1 || mask==(1<<ofst) );
drh24efa542018-10-02 19:36:40 +00004888 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan8337da62020-08-28 19:27:15 +00004889 assert( assertLockingArrayOk(pShmNode) );
drh73b64e42010-05-30 19:55:15 +00004890 if( flags & SQLITE_SHM_UNLOCK ){
dan6acdee62020-08-28 20:01:06 +00004891 if( (p->exclMask|p->sharedMask) & mask ){
4892 int ii;
4893 int bUnlock = 1;
drh73b64e42010-05-30 19:55:15 +00004894
dan6acdee62020-08-28 20:01:06 +00004895 for(ii=ofst; ii<ofst+n; ii++){
4896 if( aLock[ii]>((p->sharedMask & (1<<ii)) ? 1 : 0) ){
4897 bUnlock = 0;
4898 }
dan8337da62020-08-28 19:27:15 +00004899 }
drh73b64e42010-05-30 19:55:15 +00004900
dan6acdee62020-08-28 20:01:06 +00004901 if( bUnlock ){
4902 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
4903 if( rc==SQLITE_OK ){
4904 memset(&aLock[ofst], 0, sizeof(int)*n);
4905 }
4906 }else if( p->sharedMask & (1<<ofst) ){
4907 assert( n==1 && aLock[ofst]>1 );
4908 aLock[ofst]--;
4909 }
4910
4911 /* Undo the local locks */
dan8337da62020-08-28 19:27:15 +00004912 if( rc==SQLITE_OK ){
dan6acdee62020-08-28 20:01:06 +00004913 p->exclMask &= ~mask;
4914 p->sharedMask &= ~mask;
4915 }
drhd9e5c4f2010-05-12 18:01:39 +00004916 }
drh73b64e42010-05-30 19:55:15 +00004917 }else if( flags & SQLITE_SHM_SHARED ){
dan8337da62020-08-28 19:27:15 +00004918 assert( n==1 );
4919 assert( (p->exclMask & (1<<ofst))==0 );
4920 if( (p->sharedMask & mask)==0 ){
4921 if( aLock[ofst]<0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004922 rc = SQLITE_BUSY;
dan8337da62020-08-28 19:27:15 +00004923 }else if( aLock[ofst]==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004924 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004925 }
drh73b64e42010-05-30 19:55:15 +00004926
dan8337da62020-08-28 19:27:15 +00004927 /* Get the local shared locks */
4928 if( rc==SQLITE_OK ){
4929 p->sharedMask |= mask;
4930 aLock[ofst]++;
4931 }
drh73b64e42010-05-30 19:55:15 +00004932 }
4933 }else{
4934 /* Make sure no sibling connections hold locks that will block this
dan8337da62020-08-28 19:27:15 +00004935 ** lock. If any do, return SQLITE_BUSY right away. */
4936 int ii;
4937 for(ii=ofst; ii<ofst+n; ii++){
4938 assert( (p->sharedMask & mask)==0 );
4939 if( (p->exclMask & (1<<ii))==0 && aLock[ii] ){
drh73b64e42010-05-30 19:55:15 +00004940 rc = SQLITE_BUSY;
4941 break;
4942 }
4943 }
dan8337da62020-08-28 19:27:15 +00004944
4945 /* Get the exclusive locks at the system level. Then if successful
4946 ** also update the in-memory values. */
drh73b64e42010-05-30 19:55:15 +00004947 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004948 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004949 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004950 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004951 p->exclMask |= mask;
dan8337da62020-08-28 19:27:15 +00004952 for(ii=ofst; ii<ofst+n; ii++){
4953 aLock[ii] = -1;
4954 }
drhd9e5c4f2010-05-12 18:01:39 +00004955 }
drhd9e5c4f2010-05-12 18:01:39 +00004956 }
4957 }
dan8337da62020-08-28 19:27:15 +00004958 assert( assertLockingArrayOk(pShmNode) );
drh24efa542018-10-02 19:36:40 +00004959 sqlite3_mutex_leave(pShmNode->pShmMutex);
drh20e1f082010-05-31 16:10:12 +00004960 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004961 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004962 return rc;
4963}
4964
drh286a2882010-05-20 23:51:06 +00004965/*
4966** Implement a memory barrier or memory fence on shared memory.
4967**
4968** All loads and stores begun before the barrier must complete before
4969** any load or store begun after the barrier.
4970*/
4971static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004972 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004973){
drhff828942010-06-26 21:34:06 +00004974 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004975 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
dana86acc22018-09-12 20:32:19 +00004976 assert( fd->pMethods->xLock==nolockLock
4977 || unixFileMutexNotheld((unixFile*)fd)
4978 );
drh22c733d2015-09-24 12:40:43 +00004979 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004980 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004981}
4982
dan18801912010-06-14 14:07:50 +00004983/*
danda9fe0c2010-07-13 18:44:03 +00004984** Close a connection to shared-memory. Delete the underlying
4985** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004986**
4987** If there is no shared memory associated with the connection then this
4988** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004989*/
danda9fe0c2010-07-13 18:44:03 +00004990static int unixShmUnmap(
4991 sqlite3_file *fd, /* The underlying database file */
4992 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004993){
danda9fe0c2010-07-13 18:44:03 +00004994 unixShm *p; /* The connection to be closed */
4995 unixShmNode *pShmNode; /* The underlying shared-memory file */
4996 unixShm **pp; /* For looping over sibling connections */
4997 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004998
danda9fe0c2010-07-13 18:44:03 +00004999 pDbFd = (unixFile*)fd;
5000 p = pDbFd->pShm;
5001 if( p==0 ) return SQLITE_OK;
5002 pShmNode = p->pShmNode;
5003
5004 assert( pShmNode==pDbFd->pInode->pShmNode );
5005 assert( pShmNode->pInode==pDbFd->pInode );
5006
5007 /* Remove connection p from the set of connections associated
5008 ** with pShmNode */
drh24efa542018-10-02 19:36:40 +00005009 sqlite3_mutex_enter(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00005010 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
5011 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00005012
danda9fe0c2010-07-13 18:44:03 +00005013 /* Free the connection p */
5014 sqlite3_free(p);
5015 pDbFd->pShm = 0;
drh24efa542018-10-02 19:36:40 +00005016 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00005017
5018 /* If pShmNode->nRef has reached 0, then close the underlying
5019 ** shared-memory file, too */
drh095908e2018-08-13 20:46:18 +00005020 assert( unixFileMutexNotheld(pDbFd) );
danda9fe0c2010-07-13 18:44:03 +00005021 unixEnterMutex();
5022 assert( pShmNode->nRef>0 );
5023 pShmNode->nRef--;
5024 if( pShmNode->nRef==0 ){
drh8820c8d2018-10-02 19:58:08 +00005025 if( deleteFlag && pShmNode->hShm>=0 ){
drh4bf66fd2015-02-19 02:43:02 +00005026 osUnlink(pShmNode->zFilename);
5027 }
danda9fe0c2010-07-13 18:44:03 +00005028 unixShmPurge(pDbFd);
5029 }
5030 unixLeaveMutex();
5031
5032 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00005033}
drh286a2882010-05-20 23:51:06 +00005034
danda9fe0c2010-07-13 18:44:03 +00005035
drhd9e5c4f2010-05-12 18:01:39 +00005036#else
drh6b017cc2010-06-14 18:01:46 +00005037# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00005038# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00005039# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00005040# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00005041#endif /* #ifndef SQLITE_OMIT_WAL */
5042
mistachkine98844f2013-08-24 00:59:24 +00005043#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00005044/*
danaef49d72013-03-25 16:28:54 +00005045** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00005046*/
danf23da962013-03-23 21:00:41 +00005047static void unixUnmapfile(unixFile *pFd){
5048 assert( pFd->nFetchOut==0 );
5049 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00005050 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00005051 pFd->pMapRegion = 0;
5052 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00005053 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00005054 }
5055}
dan5d8a1372013-03-19 19:28:06 +00005056
danaef49d72013-03-25 16:28:54 +00005057/*
dane6ecd662013-04-01 17:56:59 +00005058** Attempt to set the size of the memory mapping maintained by file
5059** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5060**
5061** If successful, this function sets the following variables:
5062**
5063** unixFile.pMapRegion
5064** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00005065** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00005066**
5067** If unsuccessful, an error message is logged via sqlite3_log() and
5068** the three variables above are zeroed. In this case SQLite should
5069** continue accessing the database using the xRead() and xWrite()
5070** methods.
5071*/
5072static void unixRemapfile(
5073 unixFile *pFd, /* File descriptor object */
5074 i64 nNew /* Required mapping size */
5075){
dan4ff7bc42013-04-02 12:04:09 +00005076 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00005077 int h = pFd->h; /* File descriptor open on db file */
5078 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00005079 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00005080 u8 *pNew = 0; /* Location of new mapping */
5081 int flags = PROT_READ; /* Flags to pass to mmap() */
5082
5083 assert( pFd->nFetchOut==0 );
5084 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00005085 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00005086 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00005087 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00005088 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00005089
danfe33e392015-11-17 20:56:06 +00005090#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00005091 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00005092#endif
dane6ecd662013-04-01 17:56:59 +00005093
5094 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00005095#if HAVE_MREMAP
5096 i64 nReuse = pFd->mmapSize;
5097#else
danbc760632014-03-20 09:42:09 +00005098 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00005099 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00005100#endif
dane6ecd662013-04-01 17:56:59 +00005101 u8 *pReq = &pOrig[nReuse];
5102
5103 /* Unmap any pages of the existing mapping that cannot be reused. */
5104 if( nReuse!=nOrig ){
5105 osMunmap(pReq, nOrig-nReuse);
5106 }
5107
5108#if HAVE_MREMAP
5109 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00005110 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00005111#else
5112 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5113 if( pNew!=MAP_FAILED ){
5114 if( pNew!=pReq ){
5115 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00005116 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00005117 }else{
5118 pNew = pOrig;
5119 }
5120 }
5121#endif
5122
dan48ccef82013-04-02 20:55:01 +00005123 /* The attempt to extend the existing mapping failed. Free it. */
5124 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00005125 osMunmap(pOrig, nReuse);
5126 }
5127 }
5128
5129 /* If pNew is still NULL, try to create an entirely new mapping. */
5130 if( pNew==0 ){
5131 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00005132 }
5133
dan4ff7bc42013-04-02 12:04:09 +00005134 if( pNew==MAP_FAILED ){
5135 pNew = 0;
5136 nNew = 0;
5137 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5138
5139 /* If the mmap() above failed, assume that all subsequent mmap() calls
5140 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5141 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00005142 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00005143 }
dane6ecd662013-04-01 17:56:59 +00005144 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00005145 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00005146}
5147
5148/*
danaef49d72013-03-25 16:28:54 +00005149** Memory map or remap the file opened by file-descriptor pFd (if the file
5150** is already mapped, the existing mapping is replaced by the new). Or, if
5151** there already exists a mapping for this file, and there are still
5152** outstanding xFetch() references to it, this function is a no-op.
5153**
5154** If parameter nByte is non-negative, then it is the requested size of
5155** the mapping to create. Otherwise, if nByte is less than zero, then the
5156** requested size is the size of the file on disk. The actual size of the
5157** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00005158** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00005159**
5160** SQLITE_OK is returned if no error occurs (even if the mapping is not
5161** recreated as a result of outstanding references) or an SQLite error
5162** code otherwise.
5163*/
drhf3b1ed02015-12-02 13:11:03 +00005164static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00005165 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00005166 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005167 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5168
5169 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00005170 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00005171 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00005172 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00005173 }
drh3044b512014-06-16 16:41:52 +00005174 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00005175 }
drh9b4c59f2013-04-15 17:03:42 +00005176 if( nMap>pFd->mmapSizeMax ){
5177 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00005178 }
5179
drh333e6ca2015-12-02 15:44:39 +00005180 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005181 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00005182 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00005183 }
5184
danf23da962013-03-23 21:00:41 +00005185 return SQLITE_OK;
5186}
mistachkine98844f2013-08-24 00:59:24 +00005187#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00005188
danaef49d72013-03-25 16:28:54 +00005189/*
5190** If possible, return a pointer to a mapping of file fd starting at offset
5191** iOff. The mapping must be valid for at least nAmt bytes.
5192**
5193** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5194** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5195** Finally, if an error does occur, return an SQLite error code. The final
5196** value of *pp is undefined in this case.
5197**
5198** If this function does return a pointer, the caller must eventually
5199** release the reference by calling unixUnfetch().
5200*/
danf23da962013-03-23 21:00:41 +00005201static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00005202#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00005203 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00005204#endif
danf23da962013-03-23 21:00:41 +00005205 *pp = 0;
5206
drh9b4c59f2013-04-15 17:03:42 +00005207#if SQLITE_MAX_MMAP_SIZE>0
5208 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00005209 if( pFd->pMapRegion==0 ){
5210 int rc = unixMapfile(pFd, -1);
5211 if( rc!=SQLITE_OK ) return rc;
5212 }
5213 if( pFd->mmapSize >= iOff+nAmt ){
5214 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5215 pFd->nFetchOut++;
5216 }
5217 }
drh6e0b6d52013-04-09 16:19:20 +00005218#endif
danf23da962013-03-23 21:00:41 +00005219 return SQLITE_OK;
5220}
5221
danaef49d72013-03-25 16:28:54 +00005222/*
dandf737fe2013-03-25 17:00:24 +00005223** If the third argument is non-NULL, then this function releases a
5224** reference obtained by an earlier call to unixFetch(). The second
5225** argument passed to this function must be the same as the corresponding
5226** argument that was passed to the unixFetch() invocation.
5227**
5228** Or, if the third argument is NULL, then this function is being called
5229** to inform the VFS layer that, according to POSIX, any existing mapping
5230** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005231*/
dandf737fe2013-03-25 17:00:24 +00005232static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005233#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005234 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005235 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005236
danaef49d72013-03-25 16:28:54 +00005237 /* If p==0 (unmap the entire file) then there must be no outstanding
5238 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5239 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005240 assert( (p==0)==(pFd->nFetchOut==0) );
5241
dandf737fe2013-03-25 17:00:24 +00005242 /* If p!=0, it must match the iOff value. */
5243 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5244
danf23da962013-03-23 21:00:41 +00005245 if( p ){
5246 pFd->nFetchOut--;
5247 }else{
5248 unixUnmapfile(pFd);
5249 }
5250
5251 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005252#else
5253 UNUSED_PARAMETER(fd);
5254 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005255 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005256#endif
danf23da962013-03-23 21:00:41 +00005257 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005258}
5259
5260/*
drh734c9862008-11-28 15:37:20 +00005261** Here ends the implementation of all sqlite3_file methods.
5262**
5263********************** End sqlite3_file Methods *******************************
5264******************************************************************************/
5265
5266/*
drh6b9d6dd2008-12-03 19:34:47 +00005267** This division contains definitions of sqlite3_io_methods objects that
5268** implement various file locking strategies. It also contains definitions
5269** of "finder" functions. A finder-function is used to locate the appropriate
5270** sqlite3_io_methods object for a particular database file. The pAppData
5271** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5272** the correct finder-function for that VFS.
5273**
5274** Most finder functions return a pointer to a fixed sqlite3_io_methods
5275** object. The only interesting finder-function is autolockIoFinder, which
5276** looks at the filesystem type and tries to guess the best locking
5277** strategy from that.
5278**
peter.d.reid60ec9142014-09-06 16:39:46 +00005279** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005280**
5281** (1) The real finder-function named "FImpt()".
5282**
dane946c392009-08-22 11:39:46 +00005283** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005284**
5285**
5286** A pointer to the F pointer is used as the pAppData value for VFS
5287** objects. We have to do this instead of letting pAppData point
5288** directly at the finder-function since C90 rules prevent a void*
5289** from be cast into a function pointer.
5290**
drh6b9d6dd2008-12-03 19:34:47 +00005291**
drh7708e972008-11-29 00:56:52 +00005292** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005293**
drh7708e972008-11-29 00:56:52 +00005294** * A constant sqlite3_io_methods object call METHOD that has locking
5295** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5296**
5297** * An I/O method finder function called FINDER that returns a pointer
5298** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005299*/
drhe6d41732015-02-21 00:49:00 +00005300#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005301static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005302 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005303 CLOSE, /* xClose */ \
5304 unixRead, /* xRead */ \
5305 unixWrite, /* xWrite */ \
5306 unixTruncate, /* xTruncate */ \
5307 unixSync, /* xSync */ \
5308 unixFileSize, /* xFileSize */ \
5309 LOCK, /* xLock */ \
5310 UNLOCK, /* xUnlock */ \
5311 CKLOCK, /* xCheckReservedLock */ \
5312 unixFileControl, /* xFileControl */ \
5313 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005314 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005315 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005316 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005317 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005318 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005319 unixFetch, /* xFetch */ \
5320 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005321}; \
drh0c2694b2009-09-03 16:23:44 +00005322static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5323 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005324 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005325} \
drh0c2694b2009-09-03 16:23:44 +00005326static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005327 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005328
5329/*
5330** Here are all of the sqlite3_io_methods objects for each of the
5331** locking strategies. Functions that return pointers to these methods
5332** are also created.
5333*/
5334IOMETHODS(
5335 posixIoFinder, /* Finder function name */
5336 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005337 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005338 unixClose, /* xClose method */
5339 unixLock, /* xLock method */
5340 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005341 unixCheckReservedLock, /* xCheckReservedLock method */
5342 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005343)
drh7708e972008-11-29 00:56:52 +00005344IOMETHODS(
5345 nolockIoFinder, /* Finder function name */
5346 nolockIoMethods, /* sqlite3_io_methods object name */
drh3e2c8422018-08-13 11:32:07 +00005347 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005348 nolockClose, /* xClose method */
5349 nolockLock, /* xLock method */
5350 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005351 nolockCheckReservedLock, /* xCheckReservedLock method */
5352 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005353)
drh7708e972008-11-29 00:56:52 +00005354IOMETHODS(
5355 dotlockIoFinder, /* Finder function name */
5356 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005357 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005358 dotlockClose, /* xClose method */
5359 dotlockLock, /* xLock method */
5360 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005361 dotlockCheckReservedLock, /* xCheckReservedLock method */
5362 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005363)
drh7708e972008-11-29 00:56:52 +00005364
drhe89b2912015-03-03 20:42:01 +00005365#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005366IOMETHODS(
5367 flockIoFinder, /* Finder function name */
5368 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005369 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005370 flockClose, /* xClose method */
5371 flockLock, /* xLock method */
5372 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005373 flockCheckReservedLock, /* xCheckReservedLock method */
5374 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005375)
drh7708e972008-11-29 00:56:52 +00005376#endif
5377
drh6c7d5c52008-11-21 20:32:33 +00005378#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005379IOMETHODS(
5380 semIoFinder, /* Finder function name */
5381 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005382 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005383 semXClose, /* xClose method */
5384 semXLock, /* xLock method */
5385 semXUnlock, /* xUnlock method */
5386 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005387 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005388)
aswiftaebf4132008-11-21 00:10:35 +00005389#endif
drh7708e972008-11-29 00:56:52 +00005390
drhd2cb50b2009-01-09 21:41:17 +00005391#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005392IOMETHODS(
5393 afpIoFinder, /* Finder function name */
5394 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005395 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005396 afpClose, /* xClose method */
5397 afpLock, /* xLock method */
5398 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005399 afpCheckReservedLock, /* xCheckReservedLock method */
5400 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005401)
drh715ff302008-12-03 22:32:44 +00005402#endif
5403
5404/*
5405** The proxy locking method is a "super-method" in the sense that it
5406** opens secondary file descriptors for the conch and lock files and
5407** it uses proxy, dot-file, AFP, and flock() locking methods on those
5408** secondary files. For this reason, the division that implements
5409** proxy locking is located much further down in the file. But we need
5410** to go ahead and define the sqlite3_io_methods and finder function
5411** for proxy locking here. So we forward declare the I/O methods.
5412*/
drhd2cb50b2009-01-09 21:41:17 +00005413#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005414static int proxyClose(sqlite3_file*);
5415static int proxyLock(sqlite3_file*, int);
5416static int proxyUnlock(sqlite3_file*, int);
5417static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005418IOMETHODS(
5419 proxyIoFinder, /* Finder function name */
5420 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005421 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005422 proxyClose, /* xClose method */
5423 proxyLock, /* xLock method */
5424 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005425 proxyCheckReservedLock, /* xCheckReservedLock method */
5426 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005427)
aswiftaebf4132008-11-21 00:10:35 +00005428#endif
drh7708e972008-11-29 00:56:52 +00005429
drh7ed97b92010-01-20 13:07:21 +00005430/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5431#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5432IOMETHODS(
5433 nfsIoFinder, /* Finder function name */
5434 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005435 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005436 unixClose, /* xClose method */
5437 unixLock, /* xLock method */
5438 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005439 unixCheckReservedLock, /* xCheckReservedLock method */
5440 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005441)
5442#endif
drh7708e972008-11-29 00:56:52 +00005443
drhd2cb50b2009-01-09 21:41:17 +00005444#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005445/*
drh6b9d6dd2008-12-03 19:34:47 +00005446** This "finder" function attempts to determine the best locking strategy
5447** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005448** object that implements that strategy.
5449**
5450** This is for MacOSX only.
5451*/
drh1875f7a2008-12-08 18:19:17 +00005452static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005453 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005454 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005455){
5456 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005457 const char *zFilesystem; /* Filesystem type name */
5458 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005459 } aMap[] = {
5460 { "hfs", &posixIoMethods },
5461 { "ufs", &posixIoMethods },
5462 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005463 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005464 { "webdav", &nolockIoMethods },
5465 { 0, 0 }
5466 };
5467 int i;
5468 struct statfs fsInfo;
5469 struct flock lockInfo;
5470
5471 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005472 /* If filePath==NULL that means we are dealing with a transient file
5473 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005474 return &nolockIoMethods;
5475 }
5476 if( statfs(filePath, &fsInfo) != -1 ){
5477 if( fsInfo.f_flags & MNT_RDONLY ){
5478 return &nolockIoMethods;
5479 }
5480 for(i=0; aMap[i].zFilesystem; i++){
5481 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5482 return aMap[i].pMethods;
5483 }
5484 }
5485 }
5486
5487 /* Default case. Handles, amongst others, "nfs".
5488 ** Test byte-range lock using fcntl(). If the call succeeds,
5489 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005490 */
drh7708e972008-11-29 00:56:52 +00005491 lockInfo.l_len = 1;
5492 lockInfo.l_start = 0;
5493 lockInfo.l_whence = SEEK_SET;
5494 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005495 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005496 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5497 return &nfsIoMethods;
5498 } else {
5499 return &posixIoMethods;
5500 }
drh7708e972008-11-29 00:56:52 +00005501 }else{
5502 return &dotlockIoMethods;
5503 }
5504}
drh0c2694b2009-09-03 16:23:44 +00005505static const sqlite3_io_methods
5506 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005507
drhd2cb50b2009-01-09 21:41:17 +00005508#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005509
drhe89b2912015-03-03 20:42:01 +00005510#if OS_VXWORKS
5511/*
5512** This "finder" function for VxWorks checks to see if posix advisory
5513** locking works. If it does, then that is what is used. If it does not
5514** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005515*/
drhe89b2912015-03-03 20:42:01 +00005516static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005517 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005518 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005519){
5520 struct flock lockInfo;
5521
5522 if( !filePath ){
5523 /* If filePath==NULL that means we are dealing with a transient file
5524 ** that does not need to be locked. */
5525 return &nolockIoMethods;
5526 }
5527
5528 /* Test if fcntl() is supported and use POSIX style locks.
5529 ** Otherwise fall back to the named semaphore method.
5530 */
5531 lockInfo.l_len = 1;
5532 lockInfo.l_start = 0;
5533 lockInfo.l_whence = SEEK_SET;
5534 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005535 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005536 return &posixIoMethods;
5537 }else{
5538 return &semIoMethods;
5539 }
5540}
drh0c2694b2009-09-03 16:23:44 +00005541static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005542 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005543
drhe89b2912015-03-03 20:42:01 +00005544#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005545
drh7708e972008-11-29 00:56:52 +00005546/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005547** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005548*/
drh0c2694b2009-09-03 16:23:44 +00005549typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005550
aswiftaebf4132008-11-21 00:10:35 +00005551
drh734c9862008-11-28 15:37:20 +00005552/****************************************************************************
5553**************************** sqlite3_vfs methods ****************************
5554**
5555** This division contains the implementation of methods on the
5556** sqlite3_vfs object.
5557*/
5558
danielk1977a3d4c882007-03-23 10:08:38 +00005559/*
danielk1977e339d652008-06-28 11:23:00 +00005560** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005561*/
5562static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005563 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005564 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005565 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005566 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005567 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005568){
drh7708e972008-11-29 00:56:52 +00005569 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005570 unixFile *pNew = (unixFile *)pId;
5571 int rc = SQLITE_OK;
5572
drh8af6c222010-05-14 12:43:01 +00005573 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005574
drhb07028f2011-10-14 21:49:18 +00005575 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005576 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005577
drh308c2a52010-05-14 11:30:18 +00005578 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005579 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005580 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005581 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005582 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005583#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005584 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005585#endif
drhc02a43a2012-01-10 23:18:38 +00005586 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5587 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005588 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005589 }
drh503a6862013-03-01 01:07:17 +00005590 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005591 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005592 }
drh339eb0b2008-03-07 15:34:11 +00005593
drh6c7d5c52008-11-21 20:32:33 +00005594#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005595 pNew->pId = vxworksFindFileId(zFilename);
5596 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005597 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005598 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005599 }
5600#endif
5601
drhc02a43a2012-01-10 23:18:38 +00005602 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005603 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005604 }else{
drh0c2694b2009-09-03 16:23:44 +00005605 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005606#if SQLITE_ENABLE_LOCKING_STYLE
5607 /* Cache zFilename in the locking context (AFP and dotlock override) for
5608 ** proxyLock activation is possible (remote proxy is based on db name)
5609 ** zFilename remains valid until file is closed, to support */
5610 pNew->lockingContext = (void*)zFilename;
5611#endif
drhda0e7682008-07-30 15:27:54 +00005612 }
danielk1977e339d652008-06-28 11:23:00 +00005613
drh7ed97b92010-01-20 13:07:21 +00005614 if( pLockingStyle == &posixIoMethods
5615#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5616 || pLockingStyle == &nfsIoMethods
5617#endif
5618 ){
drh7708e972008-11-29 00:56:52 +00005619 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005620 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005621 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005622 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005623 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005624 ** in two scenarios:
5625 **
5626 ** (a) A call to fstat() failed.
5627 ** (b) A malloc failed.
5628 **
5629 ** Scenario (b) may only occur if the process is holding no other
5630 ** file descriptors open on the same file. If there were other file
5631 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005632 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005633 ** handle h - as it is guaranteed that no posix locks will be released
5634 ** by doing so.
5635 **
5636 ** If scenario (a) caused the error then things are not so safe. The
5637 ** implicit assumption here is that if fstat() fails, things are in
5638 ** such bad shape that dropping a lock or two doesn't matter much.
5639 */
drh0e9365c2011-03-02 02:08:13 +00005640 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005641 h = -1;
5642 }
drh7708e972008-11-29 00:56:52 +00005643 unixLeaveMutex();
5644 }
danielk1977e339d652008-06-28 11:23:00 +00005645
drhd2cb50b2009-01-09 21:41:17 +00005646#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005647 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005648 /* AFP locking uses the file path so it needs to be included in
5649 ** the afpLockingContext.
5650 */
5651 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005652 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005653 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005654 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005655 }else{
5656 /* NB: zFilename exists and remains valid until the file is closed
5657 ** according to requirement F11141. So we do not need to make a
5658 ** copy of the filename. */
5659 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005660 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005661 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005662 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005663 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005664 if( rc!=SQLITE_OK ){
5665 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005666 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005667 h = -1;
5668 }
drh7708e972008-11-29 00:56:52 +00005669 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005670 }
drh7708e972008-11-29 00:56:52 +00005671 }
5672#endif
danielk1977e339d652008-06-28 11:23:00 +00005673
drh7708e972008-11-29 00:56:52 +00005674 else if( pLockingStyle == &dotlockIoMethods ){
5675 /* Dotfile locking uses the file path so it needs to be included in
5676 ** the dotlockLockingContext
5677 */
5678 char *zLockFile;
5679 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005680 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005681 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005682 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005683 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005684 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005685 }else{
5686 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005687 }
drh7708e972008-11-29 00:56:52 +00005688 pNew->lockingContext = zLockFile;
5689 }
danielk1977e339d652008-06-28 11:23:00 +00005690
drh6c7d5c52008-11-21 20:32:33 +00005691#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005692 else if( pLockingStyle == &semIoMethods ){
5693 /* Named semaphore locking uses the file path so it needs to be
5694 ** included in the semLockingContext
5695 */
5696 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005697 rc = findInodeInfo(pNew, &pNew->pInode);
5698 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5699 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005700 int n;
drh2238dcc2009-08-27 17:56:20 +00005701 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005702 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005703 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005704 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005705 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5706 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005707 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005708 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005709 }
chw97185482008-11-17 08:05:31 +00005710 }
drh7708e972008-11-29 00:56:52 +00005711 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005712 }
drh7708e972008-11-29 00:56:52 +00005713#endif
aswift5b1a2562008-08-22 00:22:35 +00005714
drh4bf66fd2015-02-19 02:43:02 +00005715 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005716#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005717 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005718 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005719 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005720 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005721 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005722 }
chw97185482008-11-17 08:05:31 +00005723#endif
danielk1977e339d652008-06-28 11:23:00 +00005724 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005725 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005726 }else{
drh0c52f5a2020-07-24 09:17:42 +00005727 pId->pMethods = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005728 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005729 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005730 }
danielk1977e339d652008-06-28 11:23:00 +00005731 return rc;
drh054889e2005-11-30 03:20:31 +00005732}
drh9c06c952005-11-26 00:25:00 +00005733
danielk1977ad94b582007-08-20 06:44:22 +00005734/*
drh8b3cf822010-06-01 21:02:51 +00005735** Return the name of a directory in which to put temporary files.
5736** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005737*/
drh7234c6d2010-06-19 15:10:09 +00005738static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005739 static const char *azDirs[] = {
5740 0,
aswiftaebf4132008-11-21 00:10:35 +00005741 0,
danielk197717b90b52008-06-06 11:11:25 +00005742 "/var/tmp",
5743 "/usr/tmp",
5744 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005745 "."
danielk197717b90b52008-06-06 11:11:25 +00005746 };
drh2aab11f2016-04-29 20:30:56 +00005747 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005748 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005749 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005750
drhb7e50ad2015-11-28 21:49:53 +00005751 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5752 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005753 while(1){
5754 if( zDir!=0
5755 && osStat(zDir, &buf)==0
5756 && S_ISDIR(buf.st_mode)
5757 && osAccess(zDir, 03)==0
5758 ){
5759 return zDir;
5760 }
5761 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5762 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005763 }
drh7694e062016-04-21 23:37:24 +00005764 return 0;
drh8b3cf822010-06-01 21:02:51 +00005765}
5766
5767/*
5768** Create a temporary file name in zBuf. zBuf must be allocated
5769** by the calling process and must be big enough to hold at least
5770** pVfs->mxPathname bytes.
5771*/
5772static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005773 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005774 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005775
5776 /* It's odd to simulate an io-error here, but really this is just
5777 ** using the io-error infrastructure to test that SQLite handles this
5778 ** function failing.
5779 */
drh7694e062016-04-21 23:37:24 +00005780 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005781 SimulateIOError( return SQLITE_IOERR );
5782
drh7234c6d2010-06-19 15:10:09 +00005783 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005784 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005785 do{
drh970942e2015-11-25 23:13:14 +00005786 u64 r;
5787 sqlite3_randomness(sizeof(r), &r);
5788 assert( nBuf>2 );
5789 zBuf[nBuf-2] = 0;
5790 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5791 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005792 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005793 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005794 return SQLITE_OK;
5795}
5796
drhd2cb50b2009-01-09 21:41:17 +00005797#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005798/*
5799** Routine to transform a unixFile into a proxy-locking unixFile.
5800** Implementation in the proxy-lock division, but used by unixOpen()
5801** if SQLITE_PREFER_PROXY_LOCKING is defined.
5802*/
5803static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005804#endif
drhc66d5b62008-12-03 22:48:32 +00005805
dan08da86a2009-08-21 17:18:03 +00005806/*
5807** Search for an unused file descriptor that was opened on the database
drh067b92b2020-06-19 15:24:12 +00005808** file (not a journal or super-journal file) identified by pathname
dan08da86a2009-08-21 17:18:03 +00005809** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5810** argument to this function.
5811**
5812** Such a file descriptor may exist if a database connection was closed
5813** but the associated file descriptor could not be closed because some
5814** other file descriptor open on the same file is holding a file-lock.
5815** Refer to comments in the unixClose() function and the lengthy comment
5816** describing "Posix Advisory Locking" at the start of this file for
5817** further details. Also, ticket #4018.
5818**
5819** If a suitable file descriptor is found, then it is returned. If no
5820** such file descriptor is located, -1 is returned.
5821*/
dane946c392009-08-22 11:39:46 +00005822static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5823 UnixUnusedFd *pUnused = 0;
5824
5825 /* Do not search for an unused file descriptor on vxworks. Not because
5826 ** vxworks would not benefit from the change (it might, we're not sure),
5827 ** but because no way to test it is currently available. It is better
5828 ** not to risk breaking vxworks support for the sake of such an obscure
5829 ** feature. */
5830#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005831 struct stat sStat; /* Results of stat() call */
5832
drhc68886b2017-08-18 16:09:52 +00005833 unixEnterMutex();
5834
dan08da86a2009-08-21 17:18:03 +00005835 /* A stat() call may fail for various reasons. If this happens, it is
5836 ** almost certain that an open() call on the same path will also fail.
5837 ** For this reason, if an error occurs in the stat() call here, it is
5838 ** ignored and -1 is returned. The caller will try to open a new file
5839 ** descriptor on the same path, fail, and return an error to SQLite.
5840 **
5841 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005842 ** not searching for a reusable file descriptor are not dire. */
drh095908e2018-08-13 20:46:18 +00005843 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005844 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005845
drh8af6c222010-05-14 12:43:01 +00005846 pInode = inodeList;
5847 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005848 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005849 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005850 }
drh8af6c222010-05-14 12:43:01 +00005851 if( pInode ){
dane946c392009-08-22 11:39:46 +00005852 UnixUnusedFd **pp;
drh095908e2018-08-13 20:46:18 +00005853 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5854 sqlite3_mutex_enter(pInode->pLockMutex);
drh55220a62019-08-06 20:55:06 +00005855 flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
drh8af6c222010-05-14 12:43:01 +00005856 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005857 pUnused = *pp;
5858 if( pUnused ){
5859 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005860 }
drh095908e2018-08-13 20:46:18 +00005861 sqlite3_mutex_leave(pInode->pLockMutex);
dan08da86a2009-08-21 17:18:03 +00005862 }
dan08da86a2009-08-21 17:18:03 +00005863 }
drhc68886b2017-08-18 16:09:52 +00005864 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005865#endif /* if !OS_VXWORKS */
5866 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005867}
danielk197717b90b52008-06-06 11:11:25 +00005868
5869/*
dan1bf4ca72016-08-11 18:05:47 +00005870** Find the mode, uid and gid of file zFile.
5871*/
5872static int getFileMode(
5873 const char *zFile, /* File name */
5874 mode_t *pMode, /* OUT: Permissions of zFile */
5875 uid_t *pUid, /* OUT: uid of zFile. */
5876 gid_t *pGid /* OUT: gid of zFile. */
5877){
5878 struct stat sStat; /* Output of stat() on database file */
5879 int rc = SQLITE_OK;
5880 if( 0==osStat(zFile, &sStat) ){
5881 *pMode = sStat.st_mode & 0777;
5882 *pUid = sStat.st_uid;
5883 *pGid = sStat.st_gid;
5884 }else{
5885 rc = SQLITE_IOERR_FSTAT;
5886 }
5887 return rc;
5888}
5889
5890/*
danddb0ac42010-07-14 14:48:58 +00005891** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005892** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005893** and a value suitable for passing as the third argument to open(2) is
5894** written to *pMode. If an IO error occurs, an SQLite error code is
5895** returned and the value of *pMode is not modified.
5896**
peter.d.reid60ec9142014-09-06 16:39:46 +00005897** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005898** an indication to robust_open() to create the file using
5899** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5900** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005901** this function queries the file-system for the permissions on the
5902** corresponding database file and sets *pMode to this value. Whenever
5903** possible, WAL and journal files are created using the same permissions
5904** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005905**
5906** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5907** original filename is unavailable. But 8_3_NAMES is only used for
5908** FAT filesystems and permissions do not matter there, so just use
drh1116b172019-09-25 10:36:31 +00005909** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
danddb0ac42010-07-14 14:48:58 +00005910*/
5911static int findCreateFileMode(
5912 const char *zPath, /* Path of file (possibly) being created */
5913 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005914 mode_t *pMode, /* OUT: Permissions to open file with */
5915 uid_t *pUid, /* OUT: uid to set on the file */
5916 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005917){
5918 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005919 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005920 *pUid = 0;
5921 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005922 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005923 char zDb[MAX_PATHNAME+1]; /* Database file path */
5924 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005925
dana0c989d2010-11-05 18:07:37 +00005926 /* zPath is a path to a WAL or journal file. The following block derives
5927 ** the path to the associated database file from zPath. This block handles
5928 ** the following naming conventions:
5929 **
5930 ** "<path to db>-journal"
5931 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005932 ** "<path to db>-journalNN"
5933 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005934 **
drhd337c5b2011-10-20 18:23:35 +00005935 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005936 ** used by the test_multiplex.c module.
5937 */
5938 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005939 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005940 /* In normal operation, the journal file name will always contain
5941 ** a '-' character. However in 8+3 filename mode, or if a corrupt
drh067b92b2020-06-19 15:24:12 +00005942 ** rollback journal specifies a super-journal with a goofy name, then
dan629ec142017-09-14 20:41:17 +00005943 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005944 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005945 nDb--;
5946 }
danddb0ac42010-07-14 14:48:58 +00005947 memcpy(zDb, zPath, nDb);
5948 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005949
dan1bf4ca72016-08-11 18:05:47 +00005950 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005951 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5952 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005953 }else if( flags & SQLITE_OPEN_URI ){
5954 /* If this is a main database file and the file was opened using a URI
5955 ** filename, check for the "modeof" parameter. If present, interpret
5956 ** its value as a filename and try to copy the mode, uid and gid from
5957 ** that file. */
5958 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5959 if( z ){
5960 rc = getFileMode(z, pMode, pUid, pGid);
5961 }
danddb0ac42010-07-14 14:48:58 +00005962 }
5963 return rc;
5964}
5965
5966/*
danielk1977ad94b582007-08-20 06:44:22 +00005967** Open the file zPath.
5968**
danielk1977b4b47412007-08-17 15:53:36 +00005969** Previously, the SQLite OS layer used three functions in place of this
5970** one:
5971**
5972** sqlite3OsOpenReadWrite();
5973** sqlite3OsOpenReadOnly();
5974** sqlite3OsOpenExclusive();
5975**
5976** These calls correspond to the following combinations of flags:
5977**
5978** ReadWrite() -> (READWRITE | CREATE)
5979** ReadOnly() -> (READONLY)
5980** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5981**
5982** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5983** true, the file was configured to be automatically deleted when the
5984** file handle closed. To achieve the same effect using this new
5985** interface, add the DELETEONCLOSE flag to those specified above for
5986** OpenExclusive().
5987*/
5988static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005989 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5990 const char *zPath, /* Pathname of file to be opened */
5991 sqlite3_file *pFile, /* The file descriptor to be filled in */
5992 int flags, /* Input flags to control the opening */
5993 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005994){
dan08da86a2009-08-21 17:18:03 +00005995 unixFile *p = (unixFile *)pFile;
5996 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005997 int openFlags = 0; /* Flags to pass to open() */
drhc398c652019-11-22 00:42:01 +00005998 int eType = flags&0x0FFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005999 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00006000 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00006001 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00006002
6003 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
6004 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
6005 int isCreate = (flags & SQLITE_OPEN_CREATE);
6006 int isReadonly = (flags & SQLITE_OPEN_READONLY);
6007 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00006008#if SQLITE_ENABLE_LOCKING_STYLE
6009 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
6010#endif
drh3d4435b2011-08-26 20:55:50 +00006011#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
6012 struct statfs fsInfo;
6013#endif
danielk1977b4b47412007-08-17 15:53:36 +00006014
drh067b92b2020-06-19 15:24:12 +00006015 /* If creating a super- or main-file journal, this function will open
danielk1977fee2d252007-08-18 10:59:19 +00006016 ** a file-descriptor on the directory too. The first time unixSync()
6017 ** is called the directory file descriptor will be fsync()ed and close()d.
6018 */
drha803a2c2017-12-13 20:02:29 +00006019 int isNewJrnl = (isCreate && (
drhccb21132020-06-19 11:34:57 +00006020 eType==SQLITE_OPEN_SUPER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00006021 || eType==SQLITE_OPEN_MAIN_JOURNAL
6022 || eType==SQLITE_OPEN_WAL
6023 ));
danielk1977fee2d252007-08-18 10:59:19 +00006024
danielk197717b90b52008-06-06 11:11:25 +00006025 /* If argument zPath is a NULL pointer, this function is required to open
6026 ** a temporary file. Use this buffer to store the file name in.
6027 */
drhc02a43a2012-01-10 23:18:38 +00006028 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00006029 const char *zName = zPath;
6030
danielk1977fee2d252007-08-18 10:59:19 +00006031 /* Check the following statements are true:
6032 **
6033 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
6034 ** (b) if CREATE is set, then READWRITE must also be set, and
6035 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00006036 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00006037 */
danielk1977b4b47412007-08-17 15:53:36 +00006038 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00006039 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00006040 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00006041 assert(isDelete==0 || isCreate);
6042
drh067b92b2020-06-19 15:24:12 +00006043 /* The main DB, main journal, WAL file and super-journal are never
danddb0ac42010-07-14 14:48:58 +00006044 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00006045 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
6046 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
drhccb21132020-06-19 11:34:57 +00006047 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006048 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00006049
danielk1977fee2d252007-08-18 10:59:19 +00006050 /* Assert that the upper layer has set one of the "file-type" flags. */
6051 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
6052 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
drhccb21132020-06-19 11:34:57 +00006053 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00006054 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00006055 );
6056
drhb00d8622014-01-01 15:18:36 +00006057 /* Detect a pid change and reset the PRNG. There is a race condition
6058 ** here such that two or more threads all trying to open databases at
6059 ** the same instant might all reset the PRNG. But multiple resets
6060 ** are harmless.
6061 */
drh5ac93652015-03-21 20:59:43 +00006062 if( randomnessPid!=osGetpid(0) ){
6063 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00006064 sqlite3_randomness(0,0);
6065 }
dan08da86a2009-08-21 17:18:03 +00006066 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00006067
dan08da86a2009-08-21 17:18:03 +00006068 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00006069 UnixUnusedFd *pUnused;
6070 pUnused = findReusableFd(zName, flags);
6071 if( pUnused ){
6072 fd = pUnused->fd;
6073 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006074 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00006075 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006076 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00006077 }
6078 }
drhc68886b2017-08-18 16:09:52 +00006079 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00006080
6081 /* Database filenames are double-zero terminated if they are not
6082 ** URIs with parameters. Hence, they can always be passed into
6083 ** sqlite3_uri_parameter(). */
6084 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
6085
dan08da86a2009-08-21 17:18:03 +00006086 }else if( !zName ){
6087 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00006088 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00006089 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00006090 if( rc!=SQLITE_OK ){
6091 return rc;
6092 }
6093 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00006094
6095 /* Generated temporary filenames are always double-zero terminated
6096 ** for use by sqlite3_uri_parameter(). */
6097 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00006098 }
6099
dan08da86a2009-08-21 17:18:03 +00006100 /* Determine the value of the flags parameter passed to POSIX function
6101 ** open(). These must be calculated even if open() is not called, as
6102 ** they may be stored as part of the file handle and used by the
6103 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00006104 if( isReadonly ) openFlags |= O_RDONLY;
6105 if( isReadWrite ) openFlags |= O_RDWR;
6106 if( isCreate ) openFlags |= O_CREAT;
6107 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
drhc398c652019-11-22 00:42:01 +00006108 openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
danielk1977b4b47412007-08-17 15:53:36 +00006109
danielk1977b4b47412007-08-17 15:53:36 +00006110 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00006111 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00006112 uid_t uid; /* Userid for the file */
6113 gid_t gid; /* Groupid for the file */
6114 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00006115 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006116 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00006117 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006118 return rc;
6119 }
drhad4f1e52011-03-04 15:43:57 +00006120 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00006121 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00006122 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00006123 if( fd<0 ){
6124 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6125 /* If unable to create a journal because the directory is not
6126 ** writable, change the error code to indicate that. */
6127 rc = SQLITE_READONLY_DIRECTORY;
6128 }else if( errno!=EISDIR && isReadWrite ){
6129 /* Failed to open the file for read/write access. Try read-only. */
6130 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6131 openFlags &= ~(O_RDWR|O_CREAT);
6132 flags |= SQLITE_OPEN_READONLY;
6133 openFlags |= O_RDONLY;
6134 isReadonly = 1;
6135 fd = robust_open(zName, openFlags, openMode);
6136 }
dan08da86a2009-08-21 17:18:03 +00006137 }
6138 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00006139 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6140 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00006141 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00006142 }
drhac7c3ac2012-02-11 19:23:48 +00006143
drh1116b172019-09-25 10:36:31 +00006144 /* The owner of the rollback journal or WAL file should always be the
6145 ** same as the owner of the database file. Try to ensure that this is
6146 ** the case. The chown() system call will be a no-op if the current
6147 ** process lacks root privileges, be we should at least try. Without
6148 ** this step, if a root process opens a database file, it can leave
6149 ** behinds a journal/WAL that is owned by root and hence make the
6150 ** database inaccessible to unprivileged processes.
6151 **
drhedf8a7b2019-09-25 11:49:36 +00006152 ** If openMode==0, then that means uid and gid are not set correctly
drh1116b172019-09-25 10:36:31 +00006153 ** (probably because SQLite is configured to use 8+3 filename mode) and
6154 ** in that case we do not want to attempt the chown().
drhac7c3ac2012-02-11 19:23:48 +00006155 */
drhedf8a7b2019-09-25 11:49:36 +00006156 if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
drh6226ca22015-11-24 15:06:28 +00006157 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00006158 }
danielk1977b4b47412007-08-17 15:53:36 +00006159 }
dan08da86a2009-08-21 17:18:03 +00006160 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00006161 if( pOutFlags ){
6162 *pOutFlags = flags;
6163 }
6164
drhc68886b2017-08-18 16:09:52 +00006165 if( p->pPreallocatedUnused ){
6166 p->pPreallocatedUnused->fd = fd;
drh55220a62019-08-06 20:55:06 +00006167 p->pPreallocatedUnused->flags =
6168 flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
dane946c392009-08-22 11:39:46 +00006169 }
6170
danielk1977b4b47412007-08-17 15:53:36 +00006171 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00006172#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006173 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00006174#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6175 zPath = sqlite3_mprintf("%s", zName);
6176 if( zPath==0 ){
6177 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00006178 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00006179 }
chw97185482008-11-17 08:05:31 +00006180#else
drh036ac7f2011-08-08 23:18:05 +00006181 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00006182#endif
danielk1977b4b47412007-08-17 15:53:36 +00006183 }
drh41022642008-11-21 00:24:42 +00006184#if SQLITE_ENABLE_LOCKING_STYLE
6185 else{
dan08da86a2009-08-21 17:18:03 +00006186 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00006187 }
6188#endif
drh7ed97b92010-01-20 13:07:21 +00006189
6190#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00006191 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00006192 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00006193 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006194 return SQLITE_IOERR_ACCESS;
6195 }
6196 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6197 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6198 }
drh4bf66fd2015-02-19 02:43:02 +00006199 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6200 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6201 }
drh7ed97b92010-01-20 13:07:21 +00006202#endif
drhc02a43a2012-01-10 23:18:38 +00006203
6204 /* Set up appropriate ctrlFlags */
6205 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6206 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00006207 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00006208 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00006209 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00006210 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6211
drh7ed97b92010-01-20 13:07:21 +00006212#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00006213#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00006214 isAutoProxy = 1;
6215#endif
6216 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00006217 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6218 int useProxy = 0;
6219
dan08da86a2009-08-21 17:18:03 +00006220 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6221 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00006222 if( envforce!=NULL ){
6223 useProxy = atoi(envforce)>0;
6224 }else{
aswiftaebf4132008-11-21 00:10:35 +00006225 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6226 }
6227 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006228 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006229 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006230 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006231 if( rc!=SQLITE_OK ){
6232 /* Use unixClose to clean up the resources added in fillInUnixFile
6233 ** and clear all the structure's references. Specifically,
6234 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6235 */
6236 unixClose(pFile);
6237 return rc;
6238 }
aswiftaebf4132008-11-21 00:10:35 +00006239 }
dane946c392009-08-22 11:39:46 +00006240 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006241 }
6242 }
6243#endif
6244
dan3ed0f1c2017-09-14 21:12:07 +00006245 assert( zPath==0 || zPath[0]=='/'
drhccb21132020-06-19 11:34:57 +00006246 || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
dan3ed0f1c2017-09-14 21:12:07 +00006247 );
drhc02a43a2012-01-10 23:18:38 +00006248 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6249
dane946c392009-08-22 11:39:46 +00006250open_finished:
6251 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006252 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006253 }
6254 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006255}
6256
dane946c392009-08-22 11:39:46 +00006257
danielk1977b4b47412007-08-17 15:53:36 +00006258/*
danielk1977fee2d252007-08-18 10:59:19 +00006259** Delete the file at zPath. If the dirSync argument is true, fsync()
6260** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006261*/
drh6b9d6dd2008-12-03 19:34:47 +00006262static int unixDelete(
6263 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6264 const char *zPath, /* Name of file to be deleted */
6265 int dirSync /* If true, fsync() directory after deleting file */
6266){
danielk1977fee2d252007-08-18 10:59:19 +00006267 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006268 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006269 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006270 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006271 if( errno==ENOENT
6272#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006273 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006274#endif
6275 ){
dan9fc5b4a2012-11-09 20:17:26 +00006276 rc = SQLITE_IOERR_DELETE_NOENT;
6277 }else{
drhb4308162012-11-09 21:40:02 +00006278 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006279 }
drhb4308162012-11-09 21:40:02 +00006280 return rc;
drh5d4feff2010-07-14 01:45:22 +00006281 }
danielk1977d39fa702008-10-16 13:27:40 +00006282#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006283 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006284 int fd;
drh90315a22011-08-10 01:52:12 +00006285 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006286 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006287 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006288 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006289 }
drh0e9365c2011-03-02 02:08:13 +00006290 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006291 }else{
6292 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006293 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006294 }
6295 }
danielk1977d138dd82008-10-15 16:02:48 +00006296#endif
danielk1977fee2d252007-08-18 10:59:19 +00006297 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006298}
6299
danielk197790949c22007-08-17 16:50:38 +00006300/*
mistachkin48864df2013-03-21 21:20:32 +00006301** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006302** test performed depends on the value of flags:
6303**
6304** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6305** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6306** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6307**
6308** Otherwise return 0.
6309*/
danielk1977861f7452008-06-05 11:39:11 +00006310static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006311 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6312 const char *zPath, /* Path of the file to examine */
6313 int flags, /* What do we want to learn about the zPath file? */
6314 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006315){
danielk1977397d65f2008-11-19 11:35:39 +00006316 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006317 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006318 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006319
drhc398c652019-11-22 00:42:01 +00006320 /* The spec says there are three possible values for flags. But only
6321 ** two of them are actually used */
6322 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
drhd260b5b2015-11-25 18:03:33 +00006323
6324 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006325 struct stat buf;
drh96e8eeb2019-12-26 00:56:50 +00006326 *pResOut = 0==osStat(zPath, &buf) &&
drh09bee572019-12-27 13:30:46 +00006327 (!S_ISREG(buf.st_mode) || buf.st_size>0);
drh0933aad2019-11-18 17:46:38 +00006328 }else{
drhc398c652019-11-22 00:42:01 +00006329 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006330 }
danielk1977861f7452008-06-05 11:39:11 +00006331 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006332}
6333
danielk1977b4b47412007-08-17 15:53:36 +00006334/*
danielk1977b4b47412007-08-17 15:53:36 +00006335**
danielk1977b4b47412007-08-17 15:53:36 +00006336*/
dane88ec182016-01-25 17:04:48 +00006337static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006338 const char *zPath, /* Input path */
6339 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006340 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006341){
dancaf6b152016-01-25 18:05:49 +00006342 int nPath = sqlite3Strlen30(zPath);
6343 int iOff = 0;
6344 if( zPath[0]!='/' ){
6345 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006346 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006347 }
dancaf6b152016-01-25 18:05:49 +00006348 iOff = sqlite3Strlen30(zOut);
6349 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006350 }
dan23496702016-01-26 13:56:42 +00006351 if( (iOff+nPath+1)>nOut ){
6352 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6353 ** even if it returns an error. */
6354 zOut[iOff] = '\0';
6355 return SQLITE_CANTOPEN_BKPT;
6356 }
dancaf6b152016-01-25 18:05:49 +00006357 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006358 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006359}
6360
dane88ec182016-01-25 17:04:48 +00006361/*
6362** Turn a relative pathname into a full pathname. The relative path
6363** is stored as a nul-terminated string in the buffer pointed to by
6364** zPath.
6365**
6366** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6367** (in this case, MAX_PATHNAME bytes). The full-path is written to
6368** this buffer before returning.
6369*/
6370static int unixFullPathname(
6371 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6372 const char *zPath, /* Possibly relative input path */
6373 int nOut, /* Size of output buffer in bytes */
6374 char *zOut /* Output buffer */
6375){
danaf1b36b2016-01-25 18:43:05 +00006376#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006377 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006378#else
6379 int rc = SQLITE_OK;
6380 int nByte;
drhc398c652019-11-22 00:42:01 +00006381 int nLink = 0; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006382 const char *zIn = zPath; /* Input path for each iteration of loop */
6383 char *zDel = 0;
6384
6385 assert( pVfs->mxPathname==MAX_PATHNAME );
6386 UNUSED_PARAMETER(pVfs);
6387
6388 /* It's odd to simulate an io-error here, but really this is just
6389 ** using the io-error infrastructure to test that SQLite handles this
6390 ** function failing. This function could fail if, for example, the
6391 ** current working directory has been unlinked.
6392 */
6393 SimulateIOError( return SQLITE_ERROR );
6394
6395 do {
6396
dancaf6b152016-01-25 18:05:49 +00006397 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6398 ** link, or false otherwise. */
6399 int bLink = 0;
6400 struct stat buf;
6401 if( osLstat(zIn, &buf)!=0 ){
6402 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006403 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006404 }
dane88ec182016-01-25 17:04:48 +00006405 }else{
dancaf6b152016-01-25 18:05:49 +00006406 bLink = S_ISLNK(buf.st_mode);
6407 }
6408
6409 if( bLink ){
drhc398c652019-11-22 00:42:01 +00006410 nLink++;
dane88ec182016-01-25 17:04:48 +00006411 if( zDel==0 ){
6412 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006413 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
drhc398c652019-11-22 00:42:01 +00006414 }else if( nLink>=SQLITE_MAX_SYMLINKS ){
dancaf6b152016-01-25 18:05:49 +00006415 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006416 }
dancaf6b152016-01-25 18:05:49 +00006417
6418 if( rc==SQLITE_OK ){
6419 nByte = osReadlink(zIn, zDel, nOut-1);
6420 if( nByte<0 ){
6421 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006422 }else{
6423 if( zDel[0]!='/' ){
6424 int n;
6425 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6426 if( nByte+n+1>nOut ){
6427 rc = SQLITE_CANTOPEN_BKPT;
6428 }else{
6429 memmove(&zDel[n], zDel, nByte+1);
6430 memcpy(zDel, zIn, n);
6431 nByte += n;
6432 }
dancaf6b152016-01-25 18:05:49 +00006433 }
6434 zDel[nByte] = '\0';
6435 }
6436 }
6437
6438 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006439 }
6440
dan23496702016-01-26 13:56:42 +00006441 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6442 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006443 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006444 }
dancaf6b152016-01-25 18:05:49 +00006445 if( bLink==0 ) break;
6446 zIn = zOut;
6447 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006448
6449 sqlite3_free(zDel);
drhc398c652019-11-22 00:42:01 +00006450 if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK;
dane88ec182016-01-25 17:04:48 +00006451 return rc;
danaf1b36b2016-01-25 18:43:05 +00006452#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006453}
6454
drh0ccebe72005-06-07 22:22:50 +00006455
drh761df872006-12-21 01:29:22 +00006456#ifndef SQLITE_OMIT_LOAD_EXTENSION
6457/*
6458** Interfaces for opening a shared library, finding entry points
6459** within the shared library, and closing the shared library.
6460*/
6461#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006462static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6463 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006464 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6465}
danielk197795c8a542007-09-01 06:51:27 +00006466
6467/*
6468** SQLite calls this function immediately after a call to unixDlSym() or
6469** unixDlOpen() fails (returns a null pointer). If a more detailed error
6470** message is available, it is written to zBufOut. If no error message
6471** is available, zBufOut is left unmodified and SQLite uses a default
6472** error message.
6473*/
danielk1977397d65f2008-11-19 11:35:39 +00006474static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006475 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006476 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006477 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006478 zErr = dlerror();
6479 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006480 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006481 }
drh6c7d5c52008-11-21 20:32:33 +00006482 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006483}
drh1875f7a2008-12-08 18:19:17 +00006484static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6485 /*
6486 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6487 ** cast into a pointer to a function. And yet the library dlsym() routine
6488 ** returns a void* which is really a pointer to a function. So how do we
6489 ** use dlsym() with -pedantic-errors?
6490 **
6491 ** Variable x below is defined to be a pointer to a function taking
6492 ** parameters void* and const char* and returning a pointer to a function.
6493 ** We initialize x by assigning it a pointer to the dlsym() function.
6494 ** (That assignment requires a cast.) Then we call the function that
6495 ** x points to.
6496 **
6497 ** This work-around is unlikely to work correctly on any system where
6498 ** you really cannot cast a function pointer into void*. But then, on the
6499 ** other hand, dlsym() will not work on such a system either, so we have
6500 ** not really lost anything.
6501 */
6502 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006503 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006504 x = (void(*(*)(void*,const char*))(void))dlsym;
6505 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006506}
danielk1977397d65f2008-11-19 11:35:39 +00006507static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6508 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006509 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006510}
danielk1977b4b47412007-08-17 15:53:36 +00006511#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6512 #define unixDlOpen 0
6513 #define unixDlError 0
6514 #define unixDlSym 0
6515 #define unixDlClose 0
6516#endif
6517
6518/*
danielk197790949c22007-08-17 16:50:38 +00006519** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006520*/
danielk1977397d65f2008-11-19 11:35:39 +00006521static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6522 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006523 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006524
drhbbd42a62004-05-22 17:41:58 +00006525 /* We have to initialize zBuf to prevent valgrind from reporting
6526 ** errors. The reports issued by valgrind are incorrect - we would
6527 ** prefer that the randomness be increased by making use of the
6528 ** uninitialized space in zBuf - but valgrind errors tend to worry
6529 ** some users. Rather than argue, it seems easier just to initialize
6530 ** the whole array and silence valgrind, even if that means less randomness
6531 ** in the random seed.
6532 **
6533 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006534 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006535 ** tests repeatable.
6536 */
danielk1977b4b47412007-08-17 15:53:36 +00006537 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006538 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006539#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006540 {
drhb00d8622014-01-01 15:18:36 +00006541 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006542 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006543 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006544 time_t t;
6545 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006546 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006547 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6548 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6549 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006550 }else{
drhc18b4042012-02-10 03:10:27 +00006551 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006552 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006553 }
drhbbd42a62004-05-22 17:41:58 +00006554 }
6555#endif
drh72cbd072008-10-14 17:58:38 +00006556 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006557}
6558
danielk1977b4b47412007-08-17 15:53:36 +00006559
drhbbd42a62004-05-22 17:41:58 +00006560/*
6561** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006562** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006563** The return value is the number of microseconds of sleep actually
6564** requested from the underlying operating system, a number which
6565** might be greater than or equal to the argument, but not less
6566** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006567*/
danielk1977397d65f2008-11-19 11:35:39 +00006568static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006569#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006570 struct timespec sp;
6571
6572 sp.tv_sec = microseconds / 1000000;
6573 sp.tv_nsec = (microseconds % 1000000) * 1000;
6574 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006575 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006576 return microseconds;
6577#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006578 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006579 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006580 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006581#else
danielk1977b4b47412007-08-17 15:53:36 +00006582 int seconds = (microseconds+999999)/1000000;
6583 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006584 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006585 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006586#endif
drh88f474a2006-01-02 20:00:12 +00006587}
6588
6589/*
drh6b9d6dd2008-12-03 19:34:47 +00006590** The following variable, if set to a non-zero value, is interpreted as
6591** the number of seconds since 1970 and is used to set the result of
6592** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006593*/
6594#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006595int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006596#endif
6597
6598/*
drhb7e8ea22010-05-03 14:32:30 +00006599** Find the current time (in Universal Coordinated Time). Write into *piNow
6600** the current time and date as a Julian Day number times 86_400_000. In
6601** other words, write into *piNow the number of milliseconds since the Julian
6602** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6603** proleptic Gregorian calendar.
6604**
drh31702252011-10-12 23:13:43 +00006605** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6606** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006607*/
6608static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6609 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006610 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006611#if defined(NO_GETTOD)
6612 time_t t;
6613 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006614 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006615#elif OS_VXWORKS
6616 struct timespec sNow;
6617 clock_gettime(CLOCK_REALTIME, &sNow);
6618 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6619#else
6620 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006621 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6622 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006623#endif
6624
6625#ifdef SQLITE_TEST
6626 if( sqlite3_current_time ){
6627 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6628 }
6629#endif
6630 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006631 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006632}
6633
drhc3dfa5e2016-01-22 19:44:03 +00006634#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006635/*
drhbbd42a62004-05-22 17:41:58 +00006636** Find the current time (in Universal Coordinated Time). Write the
6637** current time and date as a Julian Day number into *prNow and
6638** return 0. Return 1 if the time and date cannot be found.
6639*/
danielk1977397d65f2008-11-19 11:35:39 +00006640static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006641 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006642 int rc;
drhff828942010-06-26 21:34:06 +00006643 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006644 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006645 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006646 return rc;
drhbbd42a62004-05-22 17:41:58 +00006647}
drh5337dac2015-11-25 15:15:03 +00006648#else
6649# define unixCurrentTime 0
6650#endif
danielk1977b4b47412007-08-17 15:53:36 +00006651
drh6b9d6dd2008-12-03 19:34:47 +00006652/*
drh1b9f2142016-03-17 16:01:23 +00006653** The xGetLastError() method is designed to return a better
6654** low-level error message when operating-system problems come up
6655** during SQLite operation. Only the integer return code is currently
6656** used.
drh6b9d6dd2008-12-03 19:34:47 +00006657*/
danielk1977397d65f2008-11-19 11:35:39 +00006658static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6659 UNUSED_PARAMETER(NotUsed);
6660 UNUSED_PARAMETER(NotUsed2);
6661 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006662 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006663}
6664
drhf2424c52010-04-26 00:04:55 +00006665
6666/*
drh734c9862008-11-28 15:37:20 +00006667************************ End of sqlite3_vfs methods ***************************
6668******************************************************************************/
6669
drh715ff302008-12-03 22:32:44 +00006670/******************************************************************************
6671************************** Begin Proxy Locking ********************************
6672**
6673** Proxy locking is a "uber-locking-method" in this sense: It uses the
6674** other locking methods on secondary lock files. Proxy locking is a
6675** meta-layer over top of the primitive locking implemented above. For
6676** this reason, the division that implements of proxy locking is deferred
6677** until late in the file (here) after all of the other I/O methods have
6678** been defined - so that the primitive locking methods are available
6679** as services to help with the implementation of proxy locking.
6680**
6681****
6682**
6683** The default locking schemes in SQLite use byte-range locks on the
6684** database file to coordinate safe, concurrent access by multiple readers
6685** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6686** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6687** as POSIX read & write locks over fixed set of locations (via fsctl),
6688** on AFP and SMB only exclusive byte-range locks are available via fsctl
6689** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6690** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6691** address in the shared range is taken for a SHARED lock, the entire
6692** shared range is taken for an EXCLUSIVE lock):
6693**
drhf2f105d2012-08-20 15:53:54 +00006694** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006695** RESERVED_BYTE 0x40000001
6696** SHARED_RANGE 0x40000002 -> 0x40000200
6697**
6698** This works well on the local file system, but shows a nearly 100x
6699** slowdown in read performance on AFP because the AFP client disables
6700** the read cache when byte-range locks are present. Enabling the read
6701** cache exposes a cache coherency problem that is present on all OS X
6702** supported network file systems. NFS and AFP both observe the
6703** close-to-open semantics for ensuring cache coherency
6704** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6705** address the requirements for concurrent database access by multiple
6706** readers and writers
6707** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6708**
6709** To address the performance and cache coherency issues, proxy file locking
6710** changes the way database access is controlled by limiting access to a
6711** single host at a time and moving file locks off of the database file
6712** and onto a proxy file on the local file system.
6713**
6714**
6715** Using proxy locks
6716** -----------------
6717**
6718** C APIs
6719**
drh4bf66fd2015-02-19 02:43:02 +00006720** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006721** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006722** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6723** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006724**
6725**
6726** SQL pragmas
6727**
6728** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6729** PRAGMA [database.]lock_proxy_file
6730**
6731** Specifying ":auto:" means that if there is a conch file with a matching
6732** host ID in it, the proxy path in the conch file will be used, otherwise
6733** a proxy path based on the user's temp dir
6734** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6735** actual proxy file name is generated from the name and path of the
6736** database file. For example:
6737**
6738** For database path "/Users/me/foo.db"
6739** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6740**
6741** Once a lock proxy is configured for a database connection, it can not
6742** be removed, however it may be switched to a different proxy path via
6743** the above APIs (assuming the conch file is not being held by another
6744** connection or process).
6745**
6746**
6747** How proxy locking works
6748** -----------------------
6749**
6750** Proxy file locking relies primarily on two new supporting files:
6751**
6752** * conch file to limit access to the database file to a single host
6753** at a time
6754**
6755** * proxy file to act as a proxy for the advisory locks normally
6756** taken on the database
6757**
6758** The conch file - to use a proxy file, sqlite must first "hold the conch"
6759** by taking an sqlite-style shared lock on the conch file, reading the
6760** contents and comparing the host's unique host ID (see below) and lock
6761** proxy path against the values stored in the conch. The conch file is
6762** stored in the same directory as the database file and the file name
6763** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006764** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006765** host ID and/or proxy path, then the lock is escalated to an exclusive
6766** lock and the conch file contents is updated with the host ID and proxy
6767** path and the lock is downgraded to a shared lock again. If the conch
6768** is held by another process (with a shared lock), the exclusive lock
6769** will fail and SQLITE_BUSY is returned.
6770**
6771** The proxy file - a single-byte file used for all advisory file locks
6772** normally taken on the database file. This allows for safe sharing
6773** of the database file for multiple readers and writers on the same
6774** host (the conch ensures that they all use the same local lock file).
6775**
drh715ff302008-12-03 22:32:44 +00006776** Requesting the lock proxy does not immediately take the conch, it is
6777** only taken when the first request to lock database file is made.
6778** This matches the semantics of the traditional locking behavior, where
6779** opening a connection to a database file does not take a lock on it.
6780** The shared lock and an open file descriptor are maintained until
6781** the connection to the database is closed.
6782**
6783** The proxy file and the lock file are never deleted so they only need
6784** to be created the first time they are used.
6785**
6786** Configuration options
6787** ---------------------
6788**
6789** SQLITE_PREFER_PROXY_LOCKING
6790**
6791** Database files accessed on non-local file systems are
6792** automatically configured for proxy locking, lock files are
6793** named automatically using the same logic as
6794** PRAGMA lock_proxy_file=":auto:"
6795**
6796** SQLITE_PROXY_DEBUG
6797**
6798** Enables the logging of error messages during host id file
6799** retrieval and creation
6800**
drh715ff302008-12-03 22:32:44 +00006801** LOCKPROXYDIR
6802**
6803** Overrides the default directory used for lock proxy files that
6804** are named automatically via the ":auto:" setting
6805**
6806** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6807**
6808** Permissions to use when creating a directory for storing the
6809** lock proxy files, only used when LOCKPROXYDIR is not set.
6810**
6811**
6812** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6813** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6814** force proxy locking to be used for every database file opened, and 0
6815** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006816** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006817** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6818*/
6819
6820/*
6821** Proxy locking is only available on MacOSX
6822*/
drhd2cb50b2009-01-09 21:41:17 +00006823#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006824
drh715ff302008-12-03 22:32:44 +00006825/*
6826** The proxyLockingContext has the path and file structures for the remote
6827** and local proxy files in it
6828*/
6829typedef struct proxyLockingContext proxyLockingContext;
6830struct proxyLockingContext {
6831 unixFile *conchFile; /* Open conch file */
6832 char *conchFilePath; /* Name of the conch file */
6833 unixFile *lockProxy; /* Open proxy lock file */
6834 char *lockProxyPath; /* Name of the proxy lock file */
6835 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006836 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006837 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006838 void *oldLockingContext; /* Original lockingcontext to restore on close */
6839 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6840};
6841
drh7ed97b92010-01-20 13:07:21 +00006842/*
6843** The proxy lock file path for the database at dbPath is written into lPath,
6844** which must point to valid, writable memory large enough for a maxLen length
6845** file path.
drh715ff302008-12-03 22:32:44 +00006846*/
drh715ff302008-12-03 22:32:44 +00006847static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6848 int len;
6849 int dbLen;
6850 int i;
6851
6852#ifdef LOCKPROXYDIR
6853 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6854#else
6855# ifdef _CS_DARWIN_USER_TEMP_DIR
6856 {
drh7ed97b92010-01-20 13:07:21 +00006857 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006858 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006859 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006860 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006861 }
drh7ed97b92010-01-20 13:07:21 +00006862 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006863 }
6864# else
6865 len = strlcpy(lPath, "/tmp/", maxLen);
6866# endif
6867#endif
6868
6869 if( lPath[len-1]!='/' ){
6870 len = strlcat(lPath, "/", maxLen);
6871 }
6872
6873 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006874 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006875 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006876 char c = dbPath[i];
6877 lPath[i+len] = (c=='/')?'_':c;
6878 }
6879 lPath[i+len]='\0';
6880 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006881 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006882 return SQLITE_OK;
6883}
6884
drh7ed97b92010-01-20 13:07:21 +00006885/*
6886 ** Creates the lock file and any missing directories in lockPath
6887 */
6888static int proxyCreateLockPath(const char *lockPath){
6889 int i, len;
6890 char buf[MAXPATHLEN];
6891 int start = 0;
6892
6893 assert(lockPath!=NULL);
6894 /* try to create all the intermediate directories */
6895 len = (int)strlen(lockPath);
6896 buf[0] = lockPath[0];
6897 for( i=1; i<len; i++ ){
6898 if( lockPath[i] == '/' && (i - start > 0) ){
6899 /* only mkdir if leaf dir != "." or "/" or ".." */
6900 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6901 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6902 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006903 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006904 int err=errno;
6905 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006906 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006907 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006908 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006909 return err;
6910 }
6911 }
6912 }
6913 start=i+1;
6914 }
6915 buf[i] = lockPath[i];
6916 }
drh62aaa6c2015-11-21 17:27:42 +00006917 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006918 return 0;
6919}
6920
drh715ff302008-12-03 22:32:44 +00006921/*
6922** Create a new VFS file descriptor (stored in memory obtained from
6923** sqlite3_malloc) and open the file named "path" in the file descriptor.
6924**
6925** The caller is responsible not only for closing the file descriptor
6926** but also for freeing the memory associated with the file descriptor.
6927*/
drh7ed97b92010-01-20 13:07:21 +00006928static int proxyCreateUnixFile(
6929 const char *path, /* path for the new unixFile */
6930 unixFile **ppFile, /* unixFile created and returned by ref */
6931 int islockfile /* if non zero missing dirs will be created */
6932) {
6933 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006934 unixFile *pNew;
6935 int rc = SQLITE_OK;
drhc398c652019-11-22 00:42:01 +00006936 int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
drh715ff302008-12-03 22:32:44 +00006937 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006938 int terrno = 0;
6939 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006940
drh7ed97b92010-01-20 13:07:21 +00006941 /* 1. first try to open/create the file
6942 ** 2. if that fails, and this is a lock file (not-conch), try creating
6943 ** the parent directories and then try again.
6944 ** 3. if that fails, try to open the file read-only
6945 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6946 */
6947 pUnused = findReusableFd(path, openFlags);
6948 if( pUnused ){
6949 fd = pUnused->fd;
6950 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006951 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006952 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006953 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006954 }
6955 }
6956 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006957 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006958 terrno = errno;
6959 if( fd<0 && errno==ENOENT && islockfile ){
6960 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006961 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006962 }
6963 }
6964 }
6965 if( fd<0 ){
drhc398c652019-11-22 00:42:01 +00006966 openFlags = O_RDONLY | O_NOFOLLOW;
drh8c815d12012-02-13 20:16:37 +00006967 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006968 terrno = errno;
6969 }
6970 if( fd<0 ){
6971 if( islockfile ){
6972 return SQLITE_BUSY;
6973 }
6974 switch (terrno) {
6975 case EACCES:
6976 return SQLITE_PERM;
6977 case EIO:
6978 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6979 default:
drh9978c972010-02-23 17:36:32 +00006980 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006981 }
6982 }
6983
drhf3cdcdc2015-04-29 16:50:28 +00006984 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006985 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006986 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006987 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006988 }
6989 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006990 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006991 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006992 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006993 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006994 pUnused->fd = fd;
6995 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006996 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006997
drhc02a43a2012-01-10 23:18:38 +00006998 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006999 if( rc==SQLITE_OK ){
7000 *ppFile = pNew;
7001 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00007002 }
drh7ed97b92010-01-20 13:07:21 +00007003end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00007004 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007005 sqlite3_free(pNew);
7006 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00007007 return rc;
7008}
7009
drh7ed97b92010-01-20 13:07:21 +00007010#ifdef SQLITE_TEST
7011/* simulate multiple hosts by creating unique hostid file paths */
7012int sqlite3_hostid_num = 0;
7013#endif
7014
7015#define PROXY_HOSTIDLEN 16 /* conch file host id length */
7016
drhe4079e12019-09-27 16:33:27 +00007017#if HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00007018/* Not always defined in the headers as it ought to be */
7019extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00007020#endif
drh0ab216a2010-07-02 17:10:40 +00007021
drh7ed97b92010-01-20 13:07:21 +00007022/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
7023** bytes of writable memory.
7024*/
7025static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00007026 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
7027 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe4079e12019-09-27 16:33:27 +00007028#if HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00007029 {
drh4bf66fd2015-02-19 02:43:02 +00007030 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00007031 if( gethostuuid(pHostID, &timeout) ){
7032 int err = errno;
7033 if( pError ){
7034 *pError = err;
7035 }
7036 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00007037 }
drh7ed97b92010-01-20 13:07:21 +00007038 }
drh3d4435b2011-08-26 20:55:50 +00007039#else
7040 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00007041#endif
drh7ed97b92010-01-20 13:07:21 +00007042#ifdef SQLITE_TEST
7043 /* simulate multiple hosts by creating unique hostid file paths */
7044 if( sqlite3_hostid_num != 0){
7045 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
7046 }
7047#endif
7048
7049 return SQLITE_OK;
7050}
7051
7052/* The conch file contains the header, host id and lock file path
7053 */
7054#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7055#define PROXY_HEADERLEN 1 /* conch file header length */
7056#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7057#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7058
7059/*
7060** Takes an open conch file, copies the contents to a new path and then moves
7061** it back. The newly created file's file descriptor is assigned to the
7062** conch file structure and finally the original conch file descriptor is
7063** closed. Returns zero if successful.
7064*/
7065static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
7066 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7067 unixFile *conchFile = pCtx->conchFile;
7068 char tPath[MAXPATHLEN];
7069 char buf[PROXY_MAXCONCHLEN];
7070 char *cPath = pCtx->conchFilePath;
7071 size_t readLen = 0;
7072 size_t pathLen = 0;
7073 char errmsg[64] = "";
7074 int fd = -1;
7075 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00007076 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00007077
7078 /* create a new path by replace the trailing '-conch' with '-break' */
7079 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
7080 if( pathLen>MAXPATHLEN || pathLen<6 ||
7081 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00007082 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00007083 goto end_breaklock;
7084 }
7085 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00007086 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007087 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00007088 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00007089 goto end_breaklock;
7090 }
7091 /* write it out to the temporary break file */
drhc398c652019-11-22 00:42:01 +00007092 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
drh7ed97b92010-01-20 13:07:21 +00007093 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00007094 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007095 goto end_breaklock;
7096 }
drhe562be52011-03-02 18:01:10 +00007097 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00007098 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007099 goto end_breaklock;
7100 }
7101 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00007102 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007103 goto end_breaklock;
7104 }
7105 rc = 0;
7106 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00007107 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007108 conchFile->h = fd;
7109 conchFile->openFlags = O_RDWR | O_CREAT;
7110
7111end_breaklock:
7112 if( rc ){
7113 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00007114 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00007115 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007116 }
7117 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7118 }
7119 return rc;
7120}
7121
7122/* Take the requested lock on the conch file and break a stale lock if the
7123** host id matches.
7124*/
7125static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7126 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7127 unixFile *conchFile = pCtx->conchFile;
7128 int rc = SQLITE_OK;
7129 int nTries = 0;
7130 struct timespec conchModTime;
7131
drh3d4435b2011-08-26 20:55:50 +00007132 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00007133 do {
7134 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7135 nTries ++;
7136 if( rc==SQLITE_BUSY ){
7137 /* If the lock failed (busy):
7138 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7139 * 2nd try: fail if the mod time changed or host id is different, wait
7140 * 10 sec and try again
7141 * 3rd try: break the lock unless the mod time has changed.
7142 */
7143 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007144 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00007145 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007146 return SQLITE_IOERR_LOCK;
7147 }
7148
7149 if( nTries==1 ){
7150 conchModTime = buf.st_mtimespec;
7151 usleep(500000); /* wait 0.5 sec and try the lock again*/
7152 continue;
7153 }
7154
7155 assert( nTries>1 );
7156 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7157 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7158 return SQLITE_BUSY;
7159 }
7160
7161 if( nTries==2 ){
7162 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00007163 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007164 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00007165 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007166 return SQLITE_IOERR_LOCK;
7167 }
7168 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7169 /* don't break the lock if the host id doesn't match */
7170 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7171 return SQLITE_BUSY;
7172 }
7173 }else{
7174 /* don't break the lock on short read or a version mismatch */
7175 return SQLITE_BUSY;
7176 }
7177 usleep(10000000); /* wait 10 sec and try the lock again */
7178 continue;
7179 }
7180
7181 assert( nTries==3 );
7182 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7183 rc = SQLITE_OK;
7184 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00007185 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00007186 }
7187 if( !rc ){
7188 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7189 }
7190 }
7191 }
7192 } while( rc==SQLITE_BUSY && nTries<3 );
7193
7194 return rc;
7195}
7196
7197/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00007198** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7199** lockPath means that the lockPath in the conch file will be used if the
7200** host IDs match, or a new lock path will be generated automatically
7201** and written to the conch file.
7202*/
7203static int proxyTakeConch(unixFile *pFile){
7204 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7205
drh7ed97b92010-01-20 13:07:21 +00007206 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00007207 return SQLITE_OK;
7208 }else{
7209 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00007210 uuid_t myHostID;
7211 int pError = 0;
7212 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00007213 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00007214 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00007215 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00007216 int createConch = 0;
7217 int hostIdMatch = 0;
7218 int readLen = 0;
7219 int tryOldLockPath = 0;
7220 int forceNewLockPath = 0;
7221
drh308c2a52010-05-14 11:30:18 +00007222 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00007223 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007224 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007225
drh7ed97b92010-01-20 13:07:21 +00007226 rc = proxyGetHostID(myHostID, &pError);
7227 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007228 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007229 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007230 }
drh7ed97b92010-01-20 13:07:21 +00007231 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007232 if( rc!=SQLITE_OK ){
7233 goto end_takeconch;
7234 }
drh7ed97b92010-01-20 13:07:21 +00007235 /* read the existing conch file */
7236 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7237 if( readLen<0 ){
7238 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007239 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007240 rc = SQLITE_IOERR_READ;
7241 goto end_takeconch;
7242 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7243 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7244 /* a short read or version format mismatch means we need to create a new
7245 ** conch file.
7246 */
7247 createConch = 1;
7248 }
7249 /* if the host id matches and the lock path already exists in the conch
7250 ** we'll try to use the path there, if we can't open that path, we'll
7251 ** retry with a new auto-generated path
7252 */
7253 do { /* in case we need to try again for an :auto: named lock file */
7254
7255 if( !createConch && !forceNewLockPath ){
7256 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7257 PROXY_HOSTIDLEN);
7258 /* if the conch has data compare the contents */
7259 if( !pCtx->lockProxyPath ){
7260 /* for auto-named local lock file, just check the host ID and we'll
7261 ** use the local lock file path that's already in there
7262 */
7263 if( hostIdMatch ){
7264 size_t pathLen = (readLen - PROXY_PATHINDEX);
7265
7266 if( pathLen>=MAXPATHLEN ){
7267 pathLen=MAXPATHLEN-1;
7268 }
7269 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7270 lockPath[pathLen] = 0;
7271 tempLockPath = lockPath;
7272 tryOldLockPath = 1;
7273 /* create a copy of the lock path if the conch is taken */
7274 goto end_takeconch;
7275 }
7276 }else if( hostIdMatch
7277 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7278 readLen-PROXY_PATHINDEX)
7279 ){
7280 /* conch host and lock path match */
7281 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007282 }
drh7ed97b92010-01-20 13:07:21 +00007283 }
7284
7285 /* if the conch isn't writable and doesn't match, we can't take it */
7286 if( (conchFile->openFlags&O_RDWR) == 0 ){
7287 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007288 goto end_takeconch;
7289 }
drh7ed97b92010-01-20 13:07:21 +00007290
7291 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007292 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007293 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7294 tempLockPath = lockPath;
7295 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007296 }
drh7ed97b92010-01-20 13:07:21 +00007297
7298 /* update conch with host and path (this will fail if other process
7299 ** has a shared lock already), if the host id matches, use the big
7300 ** stick.
drh715ff302008-12-03 22:32:44 +00007301 */
drh7ed97b92010-01-20 13:07:21 +00007302 futimes(conchFile->h, NULL);
7303 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007304 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007305 /* We are trying for an exclusive lock but another thread in this
7306 ** same process is still holding a shared lock. */
7307 rc = SQLITE_BUSY;
7308 } else {
7309 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007310 }
drh715ff302008-12-03 22:32:44 +00007311 }else{
drh4bf66fd2015-02-19 02:43:02 +00007312 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007313 }
drh7ed97b92010-01-20 13:07:21 +00007314 if( rc==SQLITE_OK ){
7315 char writeBuffer[PROXY_MAXCONCHLEN];
7316 int writeSize = 0;
7317
7318 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7319 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7320 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007321 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7322 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007323 }else{
7324 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7325 }
7326 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007327 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007328 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007329 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007330 /* If we created a new conch file (not just updated the contents of a
7331 ** valid conch file), try to match the permissions of the database
7332 */
7333 if( rc==SQLITE_OK && createConch ){
7334 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007335 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007336 if( err==0 ){
7337 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7338 S_IROTH|S_IWOTH);
7339 /* try to match the database file R/W permissions, ignore failure */
7340#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007341 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007342#else
drhff812312011-02-23 13:33:46 +00007343 do{
drhe562be52011-03-02 18:01:10 +00007344 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007345 }while( rc==(-1) && errno==EINTR );
7346 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007347 int code = errno;
7348 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7349 cmode, code, strerror(code));
7350 } else {
7351 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7352 }
7353 }else{
7354 int code = errno;
7355 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7356 err, code, strerror(code));
7357#endif
7358 }
drh715ff302008-12-03 22:32:44 +00007359 }
7360 }
drh7ed97b92010-01-20 13:07:21 +00007361 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7362
7363 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007364 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007365 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007366 int fd;
drh7ed97b92010-01-20 13:07:21 +00007367 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007368 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007369 }
7370 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007371 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007372 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007373 if( fd>=0 ){
7374 pFile->h = fd;
7375 }else{
drh9978c972010-02-23 17:36:32 +00007376 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007377 during locking */
7378 }
7379 }
7380 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7381 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7382 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7383 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7384 /* we couldn't create the proxy lock file with the old lock file path
7385 ** so try again via auto-naming
7386 */
7387 forceNewLockPath = 1;
7388 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007389 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007390 }
7391 }
7392 if( rc==SQLITE_OK ){
7393 /* Need to make a copy of path if we extracted the value
7394 ** from the conch file or the path was allocated on the stack
7395 */
7396 if( tempLockPath ){
7397 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7398 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007399 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007400 }
7401 }
7402 }
7403 if( rc==SQLITE_OK ){
7404 pCtx->conchHeld = 1;
7405
7406 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7407 afpLockingContext *afpCtx;
7408 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7409 afpCtx->dbPath = pCtx->lockProxyPath;
7410 }
7411 } else {
7412 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7413 }
drh308c2a52010-05-14 11:30:18 +00007414 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7415 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007416 return rc;
drh308c2a52010-05-14 11:30:18 +00007417 } while (1); /* in case we need to retry the :auto: lock file -
7418 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007419 }
7420}
7421
7422/*
7423** If pFile holds a lock on a conch file, then release that lock.
7424*/
7425static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007426 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007427 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7428 unixFile *conchFile; /* Name of the conch file */
7429
7430 pCtx = (proxyLockingContext *)pFile->lockingContext;
7431 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007432 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007433 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007434 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007435 if( pCtx->conchHeld>0 ){
7436 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7437 }
drh715ff302008-12-03 22:32:44 +00007438 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007439 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7440 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007441 return rc;
7442}
7443
7444/*
7445** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007446** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007447** Make *pConchPath point to the new name. Return SQLITE_OK on success
7448** or SQLITE_NOMEM if unable to obtain memory.
7449**
7450** The caller is responsible for ensuring that the allocated memory
7451** space is eventually freed.
7452**
7453** *pConchPath is set to NULL if a memory allocation error occurs.
7454*/
7455static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7456 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007457 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007458 char *conchPath; /* buffer in which to construct conch name */
7459
7460 /* Allocate space for the conch filename and initialize the name to
7461 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007462 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007463 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007464 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007465 }
7466 memcpy(conchPath, dbPath, len+1);
7467
7468 /* now insert a "." before the last / character */
7469 for( i=(len-1); i>=0; i-- ){
7470 if( conchPath[i]=='/' ){
7471 i++;
7472 break;
7473 }
7474 }
7475 conchPath[i]='.';
7476 while ( i<len ){
7477 conchPath[i+1]=dbPath[i];
7478 i++;
7479 }
7480
7481 /* append the "-conch" suffix to the file */
7482 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007483 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007484
7485 return SQLITE_OK;
7486}
7487
7488
7489/* Takes a fully configured proxy locking-style unix file and switches
7490** the local lock file path
7491*/
7492static int switchLockProxyPath(unixFile *pFile, const char *path) {
7493 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7494 char *oldPath = pCtx->lockProxyPath;
7495 int rc = SQLITE_OK;
7496
drh308c2a52010-05-14 11:30:18 +00007497 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007498 return SQLITE_BUSY;
7499 }
7500
7501 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7502 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7503 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7504 return SQLITE_OK;
7505 }else{
7506 unixFile *lockProxy = pCtx->lockProxy;
7507 pCtx->lockProxy=NULL;
7508 pCtx->conchHeld = 0;
7509 if( lockProxy!=NULL ){
7510 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7511 if( rc ) return rc;
7512 sqlite3_free(lockProxy);
7513 }
7514 sqlite3_free(oldPath);
7515 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7516 }
7517
7518 return rc;
7519}
7520
7521/*
7522** pFile is a file that has been opened by a prior xOpen call. dbPath
7523** is a string buffer at least MAXPATHLEN+1 characters in size.
7524**
7525** This routine find the filename associated with pFile and writes it
7526** int dbPath.
7527*/
7528static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007529#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007530 if( pFile->pMethod == &afpIoMethods ){
7531 /* afp style keeps a reference to the db path in the filePath field
7532 ** of the struct */
drhea678832008-12-10 19:26:22 +00007533 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007534 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7535 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007536 } else
drh715ff302008-12-03 22:32:44 +00007537#endif
7538 if( pFile->pMethod == &dotlockIoMethods ){
7539 /* dot lock style uses the locking context to store the dot lock
7540 ** file path */
7541 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7542 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7543 }else{
7544 /* all other styles use the locking context to store the db file path */
7545 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007546 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007547 }
7548 return SQLITE_OK;
7549}
7550
7551/*
7552** Takes an already filled in unix file and alters it so all file locking
7553** will be performed on the local proxy lock file. The following fields
7554** are preserved in the locking context so that they can be restored and
7555** the unix structure properly cleaned up at close time:
7556** ->lockingContext
7557** ->pMethod
7558*/
7559static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7560 proxyLockingContext *pCtx;
7561 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7562 char *lockPath=NULL;
7563 int rc = SQLITE_OK;
7564
drh308c2a52010-05-14 11:30:18 +00007565 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007566 return SQLITE_BUSY;
7567 }
7568 proxyGetDbPathForUnixFile(pFile, dbPath);
7569 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7570 lockPath=NULL;
7571 }else{
7572 lockPath=(char *)path;
7573 }
7574
drh308c2a52010-05-14 11:30:18 +00007575 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007576 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007577
drhf3cdcdc2015-04-29 16:50:28 +00007578 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007579 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007580 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007581 }
7582 memset(pCtx, 0, sizeof(*pCtx));
7583
7584 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7585 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007586 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7587 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7588 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7589 ** (c) the file system is read-only, then enable no-locking access.
7590 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7591 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7592 */
7593 struct statfs fsInfo;
7594 struct stat conchInfo;
7595 int goLockless = 0;
7596
drh99ab3b12011-03-02 15:09:07 +00007597 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007598 int err = errno;
7599 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7600 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7601 }
7602 }
7603 if( goLockless ){
7604 pCtx->conchHeld = -1; /* read only FS/ lockless */
7605 rc = SQLITE_OK;
7606 }
7607 }
drh715ff302008-12-03 22:32:44 +00007608 }
7609 if( rc==SQLITE_OK && lockPath ){
7610 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7611 }
7612
7613 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007614 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7615 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007616 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007617 }
7618 }
7619 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007620 /* all memory is allocated, proxys are created and assigned,
7621 ** switch the locking context and pMethod then return.
7622 */
drh715ff302008-12-03 22:32:44 +00007623 pCtx->oldLockingContext = pFile->lockingContext;
7624 pFile->lockingContext = pCtx;
7625 pCtx->pOldMethod = pFile->pMethod;
7626 pFile->pMethod = &proxyIoMethods;
7627 }else{
7628 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007629 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007630 sqlite3_free(pCtx->conchFile);
7631 }
drhd56b1212010-08-11 06:14:15 +00007632 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007633 sqlite3_free(pCtx->conchFilePath);
7634 sqlite3_free(pCtx);
7635 }
drh308c2a52010-05-14 11:30:18 +00007636 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7637 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007638 return rc;
7639}
7640
7641
7642/*
7643** This routine handles sqlite3_file_control() calls that are specific
7644** to proxy locking.
7645*/
7646static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7647 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007648 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007649 unixFile *pFile = (unixFile*)id;
7650 if( pFile->pMethod == &proxyIoMethods ){
7651 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7652 proxyTakeConch(pFile);
7653 if( pCtx->lockProxyPath ){
7654 *(const char **)pArg = pCtx->lockProxyPath;
7655 }else{
7656 *(const char **)pArg = ":auto: (not held)";
7657 }
7658 } else {
7659 *(const char **)pArg = NULL;
7660 }
7661 return SQLITE_OK;
7662 }
drh4bf66fd2015-02-19 02:43:02 +00007663 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007664 unixFile *pFile = (unixFile*)id;
7665 int rc = SQLITE_OK;
7666 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7667 if( pArg==NULL || (const char *)pArg==0 ){
7668 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007669 /* turn off proxy locking - not supported. If support is added for
7670 ** switching proxy locking mode off then it will need to fail if
7671 ** the journal mode is WAL mode.
7672 */
drh715ff302008-12-03 22:32:44 +00007673 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7674 }else{
7675 /* turn off proxy locking - already off - NOOP */
7676 rc = SQLITE_OK;
7677 }
7678 }else{
7679 const char *proxyPath = (const char *)pArg;
7680 if( isProxyStyle ){
7681 proxyLockingContext *pCtx =
7682 (proxyLockingContext*)pFile->lockingContext;
7683 if( !strcmp(pArg, ":auto:")
7684 || (pCtx->lockProxyPath &&
7685 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7686 ){
7687 rc = SQLITE_OK;
7688 }else{
7689 rc = switchLockProxyPath(pFile, proxyPath);
7690 }
7691 }else{
7692 /* turn on proxy file locking */
7693 rc = proxyTransformUnixFile(pFile, proxyPath);
7694 }
7695 }
7696 return rc;
7697 }
7698 default: {
7699 assert( 0 ); /* The call assures that only valid opcodes are sent */
7700 }
7701 }
drh8616cff2019-07-13 16:15:23 +00007702 /*NOTREACHED*/ assert(0);
drh715ff302008-12-03 22:32:44 +00007703 return SQLITE_ERROR;
7704}
7705
7706/*
7707** Within this division (the proxying locking implementation) the procedures
7708** above this point are all utilities. The lock-related methods of the
7709** proxy-locking sqlite3_io_method object follow.
7710*/
7711
7712
7713/*
7714** This routine checks if there is a RESERVED lock held on the specified
7715** file by this or any other process. If such a lock is held, set *pResOut
7716** to a non-zero value otherwise *pResOut is set to zero. The return value
7717** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7718*/
7719static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7720 unixFile *pFile = (unixFile*)id;
7721 int rc = proxyTakeConch(pFile);
7722 if( rc==SQLITE_OK ){
7723 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007724 if( pCtx->conchHeld>0 ){
7725 unixFile *proxy = pCtx->lockProxy;
7726 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7727 }else{ /* conchHeld < 0 is lockless */
7728 pResOut=0;
7729 }
drh715ff302008-12-03 22:32:44 +00007730 }
7731 return rc;
7732}
7733
7734/*
drh308c2a52010-05-14 11:30:18 +00007735** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007736** of the following:
7737**
7738** (1) SHARED_LOCK
7739** (2) RESERVED_LOCK
7740** (3) PENDING_LOCK
7741** (4) EXCLUSIVE_LOCK
7742**
7743** Sometimes when requesting one lock state, additional lock states
7744** are inserted in between. The locking might fail on one of the later
7745** transitions leaving the lock state different from what it started but
7746** still short of its goal. The following chart shows the allowed
7747** transitions and the inserted intermediate states:
7748**
7749** UNLOCKED -> SHARED
7750** SHARED -> RESERVED
7751** SHARED -> (PENDING) -> EXCLUSIVE
7752** RESERVED -> (PENDING) -> EXCLUSIVE
7753** PENDING -> EXCLUSIVE
7754**
7755** This routine will only increase a lock. Use the sqlite3OsUnlock()
7756** routine to lower a locking level.
7757*/
drh308c2a52010-05-14 11:30:18 +00007758static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007759 unixFile *pFile = (unixFile*)id;
7760 int rc = proxyTakeConch(pFile);
7761 if( rc==SQLITE_OK ){
7762 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007763 if( pCtx->conchHeld>0 ){
7764 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007765 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7766 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007767 }else{
7768 /* conchHeld < 0 is lockless */
7769 }
drh715ff302008-12-03 22:32:44 +00007770 }
7771 return rc;
7772}
7773
7774
7775/*
drh308c2a52010-05-14 11:30:18 +00007776** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007777** must be either NO_LOCK or SHARED_LOCK.
7778**
7779** If the locking level of the file descriptor is already at or below
7780** the requested locking level, this routine is a no-op.
7781*/
drh308c2a52010-05-14 11:30:18 +00007782static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007783 unixFile *pFile = (unixFile*)id;
7784 int rc = proxyTakeConch(pFile);
7785 if( rc==SQLITE_OK ){
7786 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007787 if( pCtx->conchHeld>0 ){
7788 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007789 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7790 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007791 }else{
7792 /* conchHeld < 0 is lockless */
7793 }
drh715ff302008-12-03 22:32:44 +00007794 }
7795 return rc;
7796}
7797
7798/*
7799** Close a file that uses proxy locks.
7800*/
7801static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007802 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007803 unixFile *pFile = (unixFile*)id;
7804 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7805 unixFile *lockProxy = pCtx->lockProxy;
7806 unixFile *conchFile = pCtx->conchFile;
7807 int rc = SQLITE_OK;
7808
7809 if( lockProxy ){
7810 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7811 if( rc ) return rc;
7812 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7813 if( rc ) return rc;
7814 sqlite3_free(lockProxy);
7815 pCtx->lockProxy = 0;
7816 }
7817 if( conchFile ){
7818 if( pCtx->conchHeld ){
7819 rc = proxyReleaseConch(pFile);
7820 if( rc ) return rc;
7821 }
7822 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7823 if( rc ) return rc;
7824 sqlite3_free(conchFile);
7825 }
drhd56b1212010-08-11 06:14:15 +00007826 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007827 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007828 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007829 /* restore the original locking context and pMethod then close it */
7830 pFile->lockingContext = pCtx->oldLockingContext;
7831 pFile->pMethod = pCtx->pOldMethod;
7832 sqlite3_free(pCtx);
7833 return pFile->pMethod->xClose(id);
7834 }
7835 return SQLITE_OK;
7836}
7837
7838
7839
drhd2cb50b2009-01-09 21:41:17 +00007840#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007841/*
7842** The proxy locking style is intended for use with AFP filesystems.
7843** And since AFP is only supported on MacOSX, the proxy locking is also
7844** restricted to MacOSX.
7845**
7846**
7847******************* End of the proxy lock implementation **********************
7848******************************************************************************/
7849
drh734c9862008-11-28 15:37:20 +00007850/*
danielk1977e339d652008-06-28 11:23:00 +00007851** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007852**
7853** This routine registers all VFS implementations for unix-like operating
7854** systems. This routine, and the sqlite3_os_end() routine that follows,
7855** should be the only routines in this file that are visible from other
7856** files.
drh6b9d6dd2008-12-03 19:34:47 +00007857**
7858** This routine is called once during SQLite initialization and by a
7859** single thread. The memory allocation and mutex subsystems have not
7860** necessarily been initialized when this routine is called, and so they
7861** should not be used.
drh153c62c2007-08-24 03:51:33 +00007862*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007863int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007864 /*
7865 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007866 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7867 ** to the "finder" function. (pAppData is a pointer to a pointer because
7868 ** silly C90 rules prohibit a void* from being cast to a function pointer
7869 ** and so we have to go through the intermediate pointer to avoid problems
7870 ** when compiling with -pedantic-errors on GCC.)
7871 **
7872 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007873 ** finder-function. The finder-function returns a pointer to the
7874 ** sqlite_io_methods object that implements the desired locking
7875 ** behaviors. See the division above that contains the IOMETHODS
7876 ** macro for addition information on finder-functions.
7877 **
7878 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7879 ** object. But the "autolockIoFinder" available on MacOSX does a little
7880 ** more than that; it looks at the filesystem type that hosts the
7881 ** database file and tries to choose an locking method appropriate for
7882 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007883 */
drh7708e972008-11-29 00:56:52 +00007884 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007885 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007886 sizeof(unixFile), /* szOsFile */ \
7887 MAX_PATHNAME, /* mxPathname */ \
7888 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007889 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007890 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007891 unixOpen, /* xOpen */ \
7892 unixDelete, /* xDelete */ \
7893 unixAccess, /* xAccess */ \
7894 unixFullPathname, /* xFullPathname */ \
7895 unixDlOpen, /* xDlOpen */ \
7896 unixDlError, /* xDlError */ \
7897 unixDlSym, /* xDlSym */ \
7898 unixDlClose, /* xDlClose */ \
7899 unixRandomness, /* xRandomness */ \
7900 unixSleep, /* xSleep */ \
7901 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007902 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007903 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007904 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007905 unixGetSystemCall, /* xGetSystemCall */ \
7906 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007907 }
7908
drh6b9d6dd2008-12-03 19:34:47 +00007909 /*
7910 ** All default VFSes for unix are contained in the following array.
7911 **
7912 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7913 ** by the SQLite core when the VFS is registered. So the following
7914 ** array cannot be const.
7915 */
danielk1977e339d652008-06-28 11:23:00 +00007916 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007917#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007918 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007919#elif OS_VXWORKS
7920 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007921#else
7922 UNIXVFS("unix", posixIoFinder ),
7923#endif
7924 UNIXVFS("unix-none", nolockIoFinder ),
7925 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007926 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007927#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007928 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007929#endif
drhe89b2912015-03-03 20:42:01 +00007930#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007931 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007932#endif
drhe89b2912015-03-03 20:42:01 +00007933#if SQLITE_ENABLE_LOCKING_STYLE
7934 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007935#endif
drhd2cb50b2009-01-09 21:41:17 +00007936#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007937 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007938 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007939 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007940#endif
drh153c62c2007-08-24 03:51:33 +00007941 };
drh6b9d6dd2008-12-03 19:34:47 +00007942 unsigned int i; /* Loop counter */
7943
drh2aa5a002011-04-13 13:42:25 +00007944 /* Double-check that the aSyscall[] array has been constructed
7945 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007946 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007947
drh6b9d6dd2008-12-03 19:34:47 +00007948 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007949 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007950 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007951 }
drh56115892018-02-05 16:39:12 +00007952 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
danielk1977c0fa4c52008-06-25 17:19:00 +00007953 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007954}
danielk1977e339d652008-06-28 11:23:00 +00007955
7956/*
drh6b9d6dd2008-12-03 19:34:47 +00007957** Shutdown the operating system interface.
7958**
7959** Some operating systems might need to do some cleanup in this routine,
7960** to release dynamically allocated objects. But not on unix.
7961** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007962*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007963int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00007964 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00007965 return SQLITE_OK;
7966}
drhdce8bdb2007-08-16 13:01:44 +00007967
danielk197729bafea2008-06-26 10:41:19 +00007968#endif /* SQLITE_OS_UNIX */