blob: 5a1d396ce2dc6265eb8219d7c9ccb7a9786148f0 [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
drh6bca6512015-04-13 23:05:28 +0000108#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
109 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
110# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
111 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
112# define HAVE_GETHOSTUUID 1
113# else
114# warning "gethostuuid() is disabled."
115# endif
116#endif
117
118
drhe89b2912015-03-03 20:42:01 +0000119#if OS_VXWORKS
120# include <sys/ioctl.h>
121# include <semaphore.h>
122# include <limits.h>
123#endif /* OS_VXWORKS */
124
125#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000126# include <sys/mount.h>
127#endif
128
drhdbe4b882011-06-20 18:00:17 +0000129#ifdef HAVE_UTIME
130# include <utime.h>
131#endif
132
drh9cbe6352005-11-29 03:13:21 +0000133/*
drh7ed97b92010-01-20 13:07:21 +0000134** Allowed values of unixFile.fsFlags
135*/
136#define SQLITE_FSFLAGS_IS_MSDOS 0x1
137
138/*
drhf1a221e2006-01-15 17:27:17 +0000139** If we are to be thread-safe, include the pthreads header and define
140** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000141*/
drhd677b3d2007-08-20 22:48:41 +0000142#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000143# include <pthread.h>
144# define SQLITE_UNIX_THREADS 1
145#endif
146
147/*
148** Default permissions when creating a new file
149*/
150#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
151# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
152#endif
153
danielk1977b4b47412007-08-17 15:53:36 +0000154/*
drh5adc60b2012-04-14 13:25:11 +0000155** Default permissions when creating auto proxy dir
156*/
aswiftaebf4132008-11-21 00:10:35 +0000157#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
158# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
159#endif
160
161/*
danielk1977b4b47412007-08-17 15:53:36 +0000162** Maximum supported path-length.
163*/
164#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000165
dane88ec182016-01-25 17:04:48 +0000166/*
167** Maximum supported symbolic links
168*/
169#define SQLITE_MAX_SYMLINKS 100
170
drh91eb93c2015-03-03 19:56:20 +0000171/* Always cast the getpid() return type for compatibility with
172** kernel modules in VxWorks. */
173#define osGetpid(X) (pid_t)getpid()
174
drh734c9862008-11-28 15:37:20 +0000175/*
drh734c9862008-11-28 15:37:20 +0000176** Only set the lastErrno if the error code is a real error and not
177** a normal expected return code of SQLITE_BUSY or SQLITE_OK
178*/
179#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
180
drhd91c68f2010-05-14 14:52:25 +0000181/* Forward references */
182typedef struct unixShm unixShm; /* Connection shared memory */
183typedef struct unixShmNode unixShmNode; /* Shared memory instance */
184typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
185typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000186
187/*
dane946c392009-08-22 11:39:46 +0000188** Sometimes, after a file handle is closed by SQLite, the file descriptor
189** cannot be closed immediately. In these cases, instances of the following
190** structure are used to store the file descriptor while waiting for an
191** opportunity to either close or reuse it.
192*/
dane946c392009-08-22 11:39:46 +0000193struct UnixUnusedFd {
194 int fd; /* File descriptor to close */
195 int flags; /* Flags this file descriptor was opened with */
196 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
197};
198
199/*
drh9b35ea62008-11-29 02:20:26 +0000200** The unixFile structure is subclass of sqlite3_file specific to the unix
201** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000202*/
drh054889e2005-11-30 03:20:31 +0000203typedef struct unixFile unixFile;
204struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000205 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000206 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000207 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000208 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000209 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000210 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000211 int lastErrno; /* The unix errno from last I/O error */
212 void *lockingContext; /* Locking style specific state */
drhc68886b2017-08-18 16:09:52 +0000213 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000214 const char *zPath; /* Name of the file */
215 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000216 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000217#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000218 int nFetchOut; /* Number of outstanding xFetch refs */
219 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000220 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
221 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000222 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000223#endif
drh537dddf2012-10-26 13:46:24 +0000224 int sectorSize; /* Device sector size */
225 int deviceCharacteristics; /* Precomputed device characteristics */
drh08c6d442009-02-09 17:34:07 +0000226#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000227 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000228#endif
drh7ed97b92010-01-20 13:07:21 +0000229#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000230 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000231#endif
232#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000233 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000234#endif
drhd3d8c042012-05-29 17:02:40 +0000235#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000236 /* The next group of variables are used to track whether or not the
237 ** transaction counter in bytes 24-27 of database files are updated
238 ** whenever any part of the database changes. An assertion fault will
239 ** occur if a file is updated without also updating the transaction
240 ** counter. This test is made to avoid new problems similar to the
241 ** one described by ticket #3584.
242 */
243 unsigned char transCntrChng; /* True if the transaction counter changed */
244 unsigned char dbUpdate; /* True if any part of database file changed */
245 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000246
drh8f941bc2009-01-14 23:03:40 +0000247#endif
danf23da962013-03-23 21:00:41 +0000248
danielk1977967a4a12007-08-20 14:23:44 +0000249#ifdef SQLITE_TEST
250 /* In test mode, increase the size of this structure a bit so that
251 ** it is larger than the struct CrashFile defined in test6.c.
252 */
253 char aPadding[32];
254#endif
drh9cbe6352005-11-29 03:13:21 +0000255};
256
drhb00d8622014-01-01 15:18:36 +0000257/* This variable holds the process id (pid) from when the xRandomness()
258** method was called. If xOpen() is called from a different process id,
259** indicating that a fork() has occurred, the PRNG will be reset.
260*/
drh8cd5b252015-03-02 22:06:43 +0000261static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000262
drh0ccebe72005-06-07 22:22:50 +0000263/*
drha7e61d82011-03-12 17:02:57 +0000264** Allowed values for the unixFile.ctrlFlags bitmask:
265*/
drhf0b190d2011-07-26 16:03:07 +0000266#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
267#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
268#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000269#ifndef SQLITE_DISABLE_DIRSYNC
270# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
271#else
272# define UNIXFILE_DIRSYNC 0x00
273#endif
drhcb15f352011-12-23 01:04:17 +0000274#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000275#define UNIXFILE_DELETE 0x20 /* Delete on close */
276#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
277#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000278
279/*
drh198bf392006-01-06 21:52:49 +0000280** Include code that is common to all os_*.c files
281*/
282#include "os_common.h"
283
284/*
drh0ccebe72005-06-07 22:22:50 +0000285** Define various macros that are missing from some systems.
286*/
drhbbd42a62004-05-22 17:41:58 +0000287#ifndef O_LARGEFILE
288# define O_LARGEFILE 0
289#endif
290#ifdef SQLITE_DISABLE_LFS
291# undef O_LARGEFILE
292# define O_LARGEFILE 0
293#endif
294#ifndef O_NOFOLLOW
295# define O_NOFOLLOW 0
296#endif
297#ifndef O_BINARY
298# define O_BINARY 0
299#endif
300
301/*
drh2b4b5962005-06-15 17:47:55 +0000302** The threadid macro resolves to the thread-id or to 0. Used for
303** testing and debugging only.
304*/
drhd677b3d2007-08-20 22:48:41 +0000305#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000306#define threadid pthread_self()
307#else
308#define threadid 0
309#endif
310
drh99ab3b12011-03-02 15:09:07 +0000311/*
dane6ecd662013-04-01 17:56:59 +0000312** HAVE_MREMAP defaults to true on Linux and false everywhere else.
313*/
314#if !defined(HAVE_MREMAP)
315# if defined(__linux__) && defined(_GNU_SOURCE)
316# define HAVE_MREMAP 1
317# else
318# define HAVE_MREMAP 0
319# endif
320#endif
321
322/*
dan2ee53412014-09-06 16:49:40 +0000323** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
324** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
325*/
326#ifdef __ANDROID__
327# define lseek lseek64
328#endif
329
drhd76dba72017-07-22 16:00:34 +0000330#ifdef __linux__
331/*
332** Linux-specific IOCTL magic numbers used for controlling F2FS
333*/
danefe16972017-07-20 19:49:14 +0000334#define F2FS_IOCTL_MAGIC 0xf5
335#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
336#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
337#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
338#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
dan9d709542017-07-21 21:06:24 +0000339#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
dan9d709542017-07-21 21:06:24 +0000340#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
drhd76dba72017-07-22 16:00:34 +0000341#endif /* __linux__ */
danefe16972017-07-20 19:49:14 +0000342
343
dan2ee53412014-09-06 16:49:40 +0000344/*
drh9a3baf12011-04-25 18:01:27 +0000345** Different Unix systems declare open() in different ways. Same use
346** open(const char*,int,mode_t). Others use open(const char*,int,...).
347** The difference is important when using a pointer to the function.
348**
349** The safest way to deal with the problem is to always use this wrapper
350** which always has the same well-defined interface.
351*/
352static int posixOpen(const char *zFile, int flags, int mode){
353 return open(zFile, flags, mode);
354}
355
drh90315a22011-08-10 01:52:12 +0000356/* Forward reference */
357static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000358static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000359
drh9a3baf12011-04-25 18:01:27 +0000360/*
drh99ab3b12011-03-02 15:09:07 +0000361** Many system calls are accessed through pointer-to-functions so that
362** they may be overridden at runtime to facilitate fault injection during
363** testing and sandboxing. The following array holds the names and pointers
364** to all overrideable system calls.
365*/
366static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000367 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000368 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
369 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000370} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000371 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
372#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000373
drh58ad5802011-03-23 22:02:23 +0000374 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000375#define osClose ((int(*)(int))aSyscall[1].pCurrent)
376
drh58ad5802011-03-23 22:02:23 +0000377 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000378#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
379
drh58ad5802011-03-23 22:02:23 +0000380 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000381#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
382
drh58ad5802011-03-23 22:02:23 +0000383 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000384#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
385
386/*
387** The DJGPP compiler environment looks mostly like Unix, but it
388** lacks the fcntl() system call. So redefine fcntl() to be something
389** that always succeeds. This means that locking does not occur under
390** DJGPP. But it is DOS - what did you expect?
391*/
392#ifdef __DJGPP__
393 { "fstat", 0, 0 },
394#define osFstat(a,b,c) 0
395#else
drh58ad5802011-03-23 22:02:23 +0000396 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000397#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
398#endif
399
drh58ad5802011-03-23 22:02:23 +0000400 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000401#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
402
drh58ad5802011-03-23 22:02:23 +0000403 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000404#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000405
drh58ad5802011-03-23 22:02:23 +0000406 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000407#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
408
drhe89b2912015-03-03 20:42:01 +0000409#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000410 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000411#else
drh58ad5802011-03-23 22:02:23 +0000412 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000413#endif
414#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
415
416#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000417 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000418#else
drh58ad5802011-03-23 22:02:23 +0000419 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000420#endif
drhf9986d92016-04-18 13:09:55 +0000421#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
drhe562be52011-03-02 18:01:10 +0000422
drh58ad5802011-03-23 22:02:23 +0000423 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000424#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
425
drhe89b2912015-03-03 20:42:01 +0000426#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000427 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000428#else
drh58ad5802011-03-23 22:02:23 +0000429 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000430#endif
431#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
432 aSyscall[12].pCurrent)
433
434#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000435 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000436#else
drh58ad5802011-03-23 22:02:23 +0000437 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000438#endif
drhf9986d92016-04-18 13:09:55 +0000439#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
drhe562be52011-03-02 18:01:10 +0000440 aSyscall[13].pCurrent)
441
drh6226ca22015-11-24 15:06:28 +0000442 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000443#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000444
445#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000446 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000447#else
drh58ad5802011-03-23 22:02:23 +0000448 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000449#endif
dan0fd7d862011-03-29 10:04:23 +0000450#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000451
drh036ac7f2011-08-08 23:18:05 +0000452 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
453#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
454
drh90315a22011-08-10 01:52:12 +0000455 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
456#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
457
drh9ef6bc42011-11-04 02:24:02 +0000458 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
459#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
460
461 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
462#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
463
drhe2258a22016-01-12 00:37:55 +0000464#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000465 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000466#else
467 { "fchown", (sqlite3_syscall_ptr)0, 0 },
468#endif
dand3eaebd2012-02-13 08:50:23 +0000469#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000470
drh26f625f2018-02-19 16:34:31 +0000471#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000472 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
drh26f625f2018-02-19 16:34:31 +0000473#else
474 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
475#endif
drh6226ca22015-11-24 15:06:28 +0000476#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
477
dan4dd51442013-08-26 14:30:25 +0000478#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000479 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
480#else
481 { "mmap", (sqlite3_syscall_ptr)0, 0 },
482#endif
drh6226ca22015-11-24 15:06:28 +0000483#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000484
drhe4a08f92016-01-08 19:17:30 +0000485#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000486 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000487#else
drha8299922016-01-08 22:31:00 +0000488 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000489#endif
drh62be1fa2017-12-09 01:02:33 +0000490#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000491
drhe4a08f92016-01-08 19:17:30 +0000492#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000493 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
494#else
495 { "mremap", (sqlite3_syscall_ptr)0, 0 },
496#endif
drh6226ca22015-11-24 15:06:28 +0000497#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
498
drh24dbeae2016-01-08 22:18:00 +0000499#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000500 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000501#else
502 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
503#endif
drh6226ca22015-11-24 15:06:28 +0000504#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000505
drhe2258a22016-01-12 00:37:55 +0000506#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000507 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000508#else
509 { "readlink", (sqlite3_syscall_ptr)0, 0 },
510#endif
drh6226ca22015-11-24 15:06:28 +0000511#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000512
danaf1b36b2016-01-25 18:43:05 +0000513#if defined(HAVE_LSTAT)
514 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
515#else
516 { "lstat", (sqlite3_syscall_ptr)0, 0 },
517#endif
dancaf6b152016-01-25 18:05:49 +0000518#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000519
drhb5d013e2017-10-25 16:14:12 +0000520#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +0000521 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
drhb5d013e2017-10-25 16:14:12 +0000522#else
523 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
524#endif
dan9d709542017-07-21 21:06:24 +0000525#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
danefe16972017-07-20 19:49:14 +0000526
drhe562be52011-03-02 18:01:10 +0000527}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000528
drh6226ca22015-11-24 15:06:28 +0000529
530/*
531** On some systems, calls to fchown() will trigger a message in a security
532** log if they come from non-root processes. So avoid calling fchown() if
533** we are not running as root.
534*/
535static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000536#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000537 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000538#else
539 return 0;
drh6226ca22015-11-24 15:06:28 +0000540#endif
541}
542
drh99ab3b12011-03-02 15:09:07 +0000543/*
544** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000545** "unix" VFSes. Return SQLITE_OK opon successfully updating the
546** system call pointer, or SQLITE_NOTFOUND if there is no configurable
547** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000548*/
549static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000550 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
551 const char *zName, /* Name of system call to override */
552 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000553){
drh58ad5802011-03-23 22:02:23 +0000554 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000555 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000556
557 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000558 if( zName==0 ){
559 /* If no zName is given, restore all system calls to their default
560 ** settings and return NULL
561 */
dan51438a72011-04-02 17:00:47 +0000562 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000563 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
564 if( aSyscall[i].pDefault ){
565 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000566 }
567 }
568 }else{
569 /* If zName is specified, operate on only the one system call
570 ** specified.
571 */
572 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
573 if( strcmp(zName, aSyscall[i].zName)==0 ){
574 if( aSyscall[i].pDefault==0 ){
575 aSyscall[i].pDefault = aSyscall[i].pCurrent;
576 }
drh1df30962011-03-02 19:06:42 +0000577 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000578 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
579 aSyscall[i].pCurrent = pNewFunc;
580 break;
581 }
582 }
583 }
584 return rc;
585}
586
drh1df30962011-03-02 19:06:42 +0000587/*
588** Return the value of a system call. Return NULL if zName is not a
589** recognized system call name. NULL is also returned if the system call
590** is currently undefined.
591*/
drh58ad5802011-03-23 22:02:23 +0000592static sqlite3_syscall_ptr unixGetSystemCall(
593 sqlite3_vfs *pNotUsed,
594 const char *zName
595){
596 unsigned int i;
597
598 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000599 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
600 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
601 }
602 return 0;
603}
604
605/*
606** Return the name of the first system call after zName. If zName==NULL
607** then return the name of the first system call. Return NULL if zName
608** is the last system call or if zName is not the name of a valid
609** system call.
610*/
611static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000612 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000613
614 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000615 if( zName ){
616 for(i=0; i<ArraySize(aSyscall)-1; i++){
617 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000618 }
619 }
dan0fd7d862011-03-29 10:04:23 +0000620 for(i++; i<ArraySize(aSyscall); i++){
621 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000622 }
623 return 0;
624}
625
drhad4f1e52011-03-04 15:43:57 +0000626/*
drh77a3fdc2013-08-30 14:24:12 +0000627** Do not accept any file descriptor less than this value, in order to avoid
628** opening database file using file descriptors that are commonly used for
629** standard input, output, and error.
630*/
631#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
632# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
633#endif
634
635/*
drh8c815d12012-02-13 20:16:37 +0000636** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000637** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000638**
639** If the file creation mode "m" is 0 then set it to the default for
640** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
641** 0644) as modified by the system umask. If m is not 0, then
642** make the file creation mode be exactly m ignoring the umask.
643**
644** The m parameter will be non-zero only when creating -wal, -journal,
645** and -shm files. We want those files to have *exactly* the same
646** permissions as their original database, unadulterated by the umask.
647** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
648** transaction crashes and leaves behind hot journals, then any
649** process that is able to write to the database will also be able to
650** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000651*/
drh8c815d12012-02-13 20:16:37 +0000652static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000653 int fd;
drhe1186ab2013-01-04 20:45:13 +0000654 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000655 while(1){
drh5adc60b2012-04-14 13:25:11 +0000656#if defined(O_CLOEXEC)
657 fd = osOpen(z,f|O_CLOEXEC,m2);
658#else
659 fd = osOpen(z,f,m2);
660#endif
drh5128d002013-08-30 06:20:23 +0000661 if( fd<0 ){
662 if( errno==EINTR ) continue;
663 break;
664 }
drh77a3fdc2013-08-30 14:24:12 +0000665 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000666 osClose(fd);
667 sqlite3_log(SQLITE_WARNING,
668 "attempt to open \"%s\" as file descriptor %d", z, fd);
669 fd = -1;
670 if( osOpen("/dev/null", f, m)<0 ) break;
671 }
drhe1186ab2013-01-04 20:45:13 +0000672 if( fd>=0 ){
673 if( m!=0 ){
674 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000675 if( osFstat(fd, &statbuf)==0
676 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000677 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000678 ){
drhe1186ab2013-01-04 20:45:13 +0000679 osFchmod(fd, m);
680 }
681 }
drh5adc60b2012-04-14 13:25:11 +0000682#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000683 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000684#endif
drhe1186ab2013-01-04 20:45:13 +0000685 }
drh5adc60b2012-04-14 13:25:11 +0000686 return fd;
drhad4f1e52011-03-04 15:43:57 +0000687}
danielk197713adf8a2004-06-03 16:08:41 +0000688
drh107886a2008-11-21 22:21:50 +0000689/*
dan9359c7b2009-08-21 08:29:10 +0000690** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000691** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000692** vxworksFileId objects used by this file, all of which may be
693** shared by multiple threads.
694**
695** Function unixMutexHeld() is used to assert() that the global mutex
696** is held when required. This function is only used as part of assert()
697** statements. e.g.
698**
699** unixEnterMutex()
700** assert( unixMutexHeld() );
701** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000702*/
drh56115892018-02-05 16:39:12 +0000703static sqlite3_mutex *unixBigLock = 0;
drh107886a2008-11-21 22:21:50 +0000704static void unixEnterMutex(void){
drh56115892018-02-05 16:39:12 +0000705 sqlite3_mutex_enter(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000706}
707static void unixLeaveMutex(void){
drh56115892018-02-05 16:39:12 +0000708 sqlite3_mutex_leave(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000709}
dan9359c7b2009-08-21 08:29:10 +0000710#ifdef SQLITE_DEBUG
711static int unixMutexHeld(void) {
drh56115892018-02-05 16:39:12 +0000712 return sqlite3_mutex_held(unixBigLock);
dan9359c7b2009-08-21 08:29:10 +0000713}
714#endif
drh107886a2008-11-21 22:21:50 +0000715
drh734c9862008-11-28 15:37:20 +0000716
mistachkinfb383e92015-04-16 03:24:38 +0000717#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000718/*
719** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000720** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000721** integer lock-type.
722*/
drh308c2a52010-05-14 11:30:18 +0000723static const char *azFileLock(int eFileLock){
724 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000725 case NO_LOCK: return "NONE";
726 case SHARED_LOCK: return "SHARED";
727 case RESERVED_LOCK: return "RESERVED";
728 case PENDING_LOCK: return "PENDING";
729 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000730 }
731 return "ERROR";
732}
733#endif
734
735#ifdef SQLITE_LOCK_TRACE
736/*
737** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000738**
drh734c9862008-11-28 15:37:20 +0000739** This routine is used for troubleshooting locks on multithreaded
740** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
741** command-line option on the compiler. This code is normally
742** turned off.
743*/
744static int lockTrace(int fd, int op, struct flock *p){
745 char *zOpName, *zType;
746 int s;
747 int savedErrno;
748 if( op==F_GETLK ){
749 zOpName = "GETLK";
750 }else if( op==F_SETLK ){
751 zOpName = "SETLK";
752 }else{
drh99ab3b12011-03-02 15:09:07 +0000753 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000754 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
755 return s;
756 }
757 if( p->l_type==F_RDLCK ){
758 zType = "RDLCK";
759 }else if( p->l_type==F_WRLCK ){
760 zType = "WRLCK";
761 }else if( p->l_type==F_UNLCK ){
762 zType = "UNLCK";
763 }else{
764 assert( 0 );
765 }
766 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000767 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000768 savedErrno = errno;
769 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
770 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
771 (int)p->l_pid, s);
772 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
773 struct flock l2;
774 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000775 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000776 if( l2.l_type==F_RDLCK ){
777 zType = "RDLCK";
778 }else if( l2.l_type==F_WRLCK ){
779 zType = "WRLCK";
780 }else if( l2.l_type==F_UNLCK ){
781 zType = "UNLCK";
782 }else{
783 assert( 0 );
784 }
785 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
786 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
787 }
788 errno = savedErrno;
789 return s;
790}
drh99ab3b12011-03-02 15:09:07 +0000791#undef osFcntl
792#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000793#endif /* SQLITE_LOCK_TRACE */
794
drhff812312011-02-23 13:33:46 +0000795/*
796** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000797**
drhe6d41732015-02-21 00:49:00 +0000798** All calls to ftruncate() within this file should be made through
799** this wrapper. On the Android platform, bypassing the logic below
800** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000801*/
drhff812312011-02-23 13:33:46 +0000802static int robust_ftruncate(int h, sqlite3_int64 sz){
803 int rc;
dan2ee53412014-09-06 16:49:40 +0000804#ifdef __ANDROID__
805 /* On Android, ftruncate() always uses 32-bit offsets, even if
806 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000807 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000808 ** such attempts. */
809 if( sz>(sqlite3_int64)0x7FFFFFFF ){
810 rc = SQLITE_OK;
811 }else
812#endif
drh99ab3b12011-03-02 15:09:07 +0000813 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000814 return rc;
815}
drh734c9862008-11-28 15:37:20 +0000816
817/*
818** This routine translates a standard POSIX errno code into something
819** useful to the clients of the sqlite3 functions. Specifically, it is
820** intended to translate a variety of "try again" errors into SQLITE_BUSY
821** and a variety of "please close the file descriptor NOW" errors into
822** SQLITE_IOERR
823**
824** Errors during initialization of locks, or file system support for locks,
825** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
826*/
827static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000828 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
829 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
830 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
831 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000832 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000833 case EACCES:
drh734c9862008-11-28 15:37:20 +0000834 case EAGAIN:
835 case ETIMEDOUT:
836 case EBUSY:
837 case EINTR:
838 case ENOLCK:
839 /* random NFS retry error, unless during file system support
840 * introspection, in which it actually means what it says */
841 return SQLITE_BUSY;
842
drh734c9862008-11-28 15:37:20 +0000843 case EPERM:
844 return SQLITE_PERM;
845
drh734c9862008-11-28 15:37:20 +0000846 default:
847 return sqliteIOErr;
848 }
849}
850
851
drh734c9862008-11-28 15:37:20 +0000852/******************************************************************************
853****************** Begin Unique File ID Utility Used By VxWorks ***************
854**
855** On most versions of unix, we can get a unique ID for a file by concatenating
856** the device number and the inode number. But this does not work on VxWorks.
857** On VxWorks, a unique file id must be based on the canonical filename.
858**
859** A pointer to an instance of the following structure can be used as a
860** unique file ID in VxWorks. Each instance of this structure contains
861** a copy of the canonical filename. There is also a reference count.
862** The structure is reclaimed when the number of pointers to it drops to
863** zero.
864**
865** There are never very many files open at one time and lookups are not
866** a performance-critical path, so it is sufficient to put these
867** structures on a linked list.
868*/
869struct vxworksFileId {
870 struct vxworksFileId *pNext; /* Next in a list of them all */
871 int nRef; /* Number of references to this one */
872 int nName; /* Length of the zCanonicalName[] string */
873 char *zCanonicalName; /* Canonical filename */
874};
875
876#if OS_VXWORKS
877/*
drh9b35ea62008-11-29 02:20:26 +0000878** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000879** variable:
880*/
881static struct vxworksFileId *vxworksFileList = 0;
882
883/*
884** Simplify a filename into its canonical form
885** by making the following changes:
886**
887** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000888** * convert /./ into just /
889** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000890**
891** Changes are made in-place. Return the new name length.
892**
893** The original filename is in z[0..n-1]. Return the number of
894** characters in the simplified name.
895*/
896static int vxworksSimplifyName(char *z, int n){
897 int i, j;
898 while( n>1 && z[n-1]=='/' ){ n--; }
899 for(i=j=0; i<n; i++){
900 if( z[i]=='/' ){
901 if( z[i+1]=='/' ) continue;
902 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
903 i += 1;
904 continue;
905 }
906 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
907 while( j>0 && z[j-1]!='/' ){ j--; }
908 if( j>0 ){ j--; }
909 i += 2;
910 continue;
911 }
912 }
913 z[j++] = z[i];
914 }
915 z[j] = 0;
916 return j;
917}
918
919/*
920** Find a unique file ID for the given absolute pathname. Return
921** a pointer to the vxworksFileId object. This pointer is the unique
922** file ID.
923**
924** The nRef field of the vxworksFileId object is incremented before
925** the object is returned. A new vxworksFileId object is created
926** and added to the global list if necessary.
927**
928** If a memory allocation error occurs, return NULL.
929*/
930static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
931 struct vxworksFileId *pNew; /* search key and new file ID */
932 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
933 int n; /* Length of zAbsoluteName string */
934
935 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000936 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000937 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000938 if( pNew==0 ) return 0;
939 pNew->zCanonicalName = (char*)&pNew[1];
940 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
941 n = vxworksSimplifyName(pNew->zCanonicalName, n);
942
943 /* Search for an existing entry that matching the canonical name.
944 ** If found, increment the reference count and return a pointer to
945 ** the existing file ID.
946 */
947 unixEnterMutex();
948 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
949 if( pCandidate->nName==n
950 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
951 ){
952 sqlite3_free(pNew);
953 pCandidate->nRef++;
954 unixLeaveMutex();
955 return pCandidate;
956 }
957 }
958
959 /* No match was found. We will make a new file ID */
960 pNew->nRef = 1;
961 pNew->nName = n;
962 pNew->pNext = vxworksFileList;
963 vxworksFileList = pNew;
964 unixLeaveMutex();
965 return pNew;
966}
967
968/*
969** Decrement the reference count on a vxworksFileId object. Free
970** the object when the reference count reaches zero.
971*/
972static void vxworksReleaseFileId(struct vxworksFileId *pId){
973 unixEnterMutex();
974 assert( pId->nRef>0 );
975 pId->nRef--;
976 if( pId->nRef==0 ){
977 struct vxworksFileId **pp;
978 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
979 assert( *pp==pId );
980 *pp = pId->pNext;
981 sqlite3_free(pId);
982 }
983 unixLeaveMutex();
984}
985#endif /* OS_VXWORKS */
986/*************** End of Unique File ID Utility Used By VxWorks ****************
987******************************************************************************/
988
989
990/******************************************************************************
991*************************** Posix Advisory Locking ****************************
992**
drh9b35ea62008-11-29 02:20:26 +0000993** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000994** section 6.5.2.2 lines 483 through 490 specify that when a process
995** sets or clears a lock, that operation overrides any prior locks set
996** by the same process. It does not explicitly say so, but this implies
997** that it overrides locks set by the same process using a different
998** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000999**
1000** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +00001001** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1002**
1003** Suppose ./file1 and ./file2 are really the same file (because
1004** one is a hard or symbolic link to the other) then if you set
1005** an exclusive lock on fd1, then try to get an exclusive lock
1006** on fd2, it works. I would have expected the second lock to
1007** fail since there was already a lock on the file due to fd1.
1008** But not so. Since both locks came from the same process, the
1009** second overrides the first, even though they were on different
1010** file descriptors opened on different file names.
1011**
drh734c9862008-11-28 15:37:20 +00001012** This means that we cannot use POSIX locks to synchronize file access
1013** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001014** to synchronize access for threads in separate processes, but not
1015** threads within the same process.
1016**
1017** To work around the problem, SQLite has to manage file locks internally
1018** on its own. Whenever a new database is opened, we have to find the
1019** specific inode of the database file (the inode is determined by the
1020** st_dev and st_ino fields of the stat structure that fstat() fills in)
1021** and check for locks already existing on that inode. When locks are
1022** created or removed, we have to look at our own internal record of the
1023** locks to see if another thread has previously set a lock on that same
1024** inode.
1025**
drh9b35ea62008-11-29 02:20:26 +00001026** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1027** For VxWorks, we have to use the alternative unique ID system based on
1028** canonical filename and implemented in the previous division.)
1029**
danielk1977ad94b582007-08-20 06:44:22 +00001030** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001031** descriptor. It is now a structure that holds the integer file
1032** descriptor and a pointer to a structure that describes the internal
1033** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001034** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001035** point to the same locking structure. The locking structure keeps
1036** a reference count (so we will know when to delete it) and a "cnt"
1037** field that tells us its internal lock status. cnt==0 means the
1038** file is unlocked. cnt==-1 means the file has an exclusive lock.
1039** cnt>0 means there are cnt shared locks on the file.
1040**
1041** Any attempt to lock or unlock a file first checks the locking
1042** structure. The fcntl() system call is only invoked to set a
1043** POSIX lock if the internal lock structure transitions between
1044** a locked and an unlocked state.
1045**
drh734c9862008-11-28 15:37:20 +00001046** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001047**
1048** If you close a file descriptor that points to a file that has locks,
1049** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001050** released. To work around this problem, each unixInodeInfo object
1051** maintains a count of the number of pending locks on tha inode.
1052** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001053** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001054** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001055** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001056** be closed and that list is walked (and cleared) when the last lock
1057** clears.
1058**
drh9b35ea62008-11-29 02:20:26 +00001059** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001060**
drh9b35ea62008-11-29 02:20:26 +00001061** Many older versions of linux use the LinuxThreads library which is
1062** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001063** A cannot be modified or overridden by a different thread B.
1064** Only thread A can modify the lock. Locking behavior is correct
1065** if the appliation uses the newer Native Posix Thread Library (NPTL)
1066** on linux - with NPTL a lock created by thread A can override locks
1067** in thread B. But there is no way to know at compile-time which
1068** threading library is being used. So there is no way to know at
1069** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001070** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001071** current process.
drh5fdae772004-06-29 03:29:00 +00001072**
drh8af6c222010-05-14 12:43:01 +00001073** SQLite used to support LinuxThreads. But support for LinuxThreads
1074** was dropped beginning with version 3.7.0. SQLite will still work with
1075** LinuxThreads provided that (1) there is no more than one connection
1076** per database file in the same process and (2) database connections
1077** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001078*/
1079
1080/*
1081** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001082** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001083*/
1084struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001085 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001086#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001087 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001088#else
drh25ef7f52016-12-05 20:06:45 +00001089 /* We are told that some versions of Android contain a bug that
1090 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1091 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1092 ** To work around this, always allocate 64-bits for the inode number.
1093 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1094 ** but that should not be a big deal. */
1095 /* WAS: ino_t ino; */
1096 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001097#endif
1098};
1099
1100/*
drhbbd42a62004-05-22 17:41:58 +00001101** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001102** inode. Or, on LinuxThreads, there is one of these structures for
1103** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001104**
danielk1977ad94b582007-08-20 06:44:22 +00001105** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001106** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001107** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001108*/
drh8af6c222010-05-14 12:43:01 +00001109struct unixInodeInfo {
1110 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001111 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001112 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1113 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001114 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001115 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1116 int nLock; /* Number of outstanding file locks */
1117 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1118 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1119 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001120#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001121 unsigned long long sharedByte; /* for AFP simulated shared lock */
1122#endif
drh6c7d5c52008-11-21 20:32:33 +00001123#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001124 sem_t *pSem; /* Named POSIX semaphore */
1125 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001126#endif
drhbbd42a62004-05-22 17:41:58 +00001127};
1128
drhda0e7682008-07-30 15:27:54 +00001129/*
drh8af6c222010-05-14 12:43:01 +00001130** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001131*/
drhc68886b2017-08-18 16:09:52 +00001132static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1133static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
drh5fdae772004-06-29 03:29:00 +00001134
drh5fdae772004-06-29 03:29:00 +00001135/*
dane18d4952011-02-21 11:46:24 +00001136**
drhaaeaa182015-11-24 15:12:47 +00001137** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001138** unixLogError().
1139**
1140** It is invoked after an error occurs in an OS function and errno has been
1141** set. It logs a message using sqlite3_log() containing the current value of
1142** errno and, if possible, the human-readable equivalent from strerror() or
1143** strerror_r().
1144**
1145** The first argument passed to the macro should be the error code that
1146** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1147** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001148** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001149** if any.
1150*/
drh0e9365c2011-03-02 02:08:13 +00001151#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1152static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001153 int errcode, /* SQLite error code */
1154 const char *zFunc, /* Name of OS function that failed */
1155 const char *zPath, /* File path associated with error */
1156 int iLine /* Source line number where error occurred */
1157){
1158 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001159 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001160
1161 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1162 ** the strerror() function to obtain the human-readable error message
1163 ** equivalent to errno. Otherwise, use strerror_r().
1164 */
1165#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1166 char aErr[80];
1167 memset(aErr, 0, sizeof(aErr));
1168 zErr = aErr;
1169
1170 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001171 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001172 ** returns a pointer to a buffer containing the error message. That pointer
1173 ** may point to aErr[], or it may point to some static storage somewhere.
1174 ** Otherwise, assume that the system provides the POSIX version of
1175 ** strerror_r(), which always writes an error message into aErr[].
1176 **
1177 ** If the code incorrectly assumes that it is the POSIX version that is
1178 ** available, the error message will often be an empty string. Not a
1179 ** huge problem. Incorrectly concluding that the GNU version is available
1180 ** could lead to a segfault though.
1181 */
1182#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1183 zErr =
1184# endif
drh0e9365c2011-03-02 02:08:13 +00001185 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001186
1187#elif SQLITE_THREADSAFE
1188 /* This is a threadsafe build, but strerror_r() is not available. */
1189 zErr = "";
1190#else
1191 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001192 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001193#endif
1194
drh0e9365c2011-03-02 02:08:13 +00001195 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001196 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001197 "os_unix.c:%d: (%d) %s(%s) - %s",
1198 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001199 );
1200
1201 return errcode;
1202}
1203
drh0e9365c2011-03-02 02:08:13 +00001204/*
1205** Close a file descriptor.
1206**
1207** We assume that close() almost always works, since it is only in a
1208** very sick application or on a very sick platform that it might fail.
1209** If it does fail, simply leak the file descriptor, but do log the
1210** error.
1211**
1212** Note that it is not safe to retry close() after EINTR since the
1213** file descriptor might have already been reused by another thread.
1214** So we don't even try to recover from an EINTR. Just log the error
1215** and move on.
1216*/
1217static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001218 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001219 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1220 pFile ? pFile->zPath : 0, lineno);
1221 }
1222}
dane18d4952011-02-21 11:46:24 +00001223
1224/*
drhe6d41732015-02-21 00:49:00 +00001225** Set the pFile->lastErrno. Do this in a subroutine as that provides
1226** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001227*/
1228static void storeLastErrno(unixFile *pFile, int error){
1229 pFile->lastErrno = error;
1230}
1231
1232/*
danb0ac3e32010-06-16 10:55:42 +00001233** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001234*/
drh0e9365c2011-03-02 02:08:13 +00001235static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001236 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001237 UnixUnusedFd *p;
1238 UnixUnusedFd *pNext;
1239 for(p=pInode->pUnused; p; p=pNext){
1240 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001241 robust_close(pFile, p->fd, __LINE__);
1242 sqlite3_free(p);
drhc68886b2017-08-18 16:09:52 +00001243 nUnusedFd--;
danb0ac3e32010-06-16 10:55:42 +00001244 }
drh0e9365c2011-03-02 02:08:13 +00001245 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001246}
1247
1248/*
drh8af6c222010-05-14 12:43:01 +00001249** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001250**
1251** The mutex entered using the unixEnterMutex() function must be held
1252** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001253*/
danb0ac3e32010-06-16 10:55:42 +00001254static void releaseInodeInfo(unixFile *pFile){
1255 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001256 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001257 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001258 pInode->nRef--;
1259 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001260 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001261 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001262 if( pInode->pPrev ){
1263 assert( pInode->pPrev->pNext==pInode );
1264 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001265 }else{
drh8af6c222010-05-14 12:43:01 +00001266 assert( inodeList==pInode );
1267 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001268 }
drh8af6c222010-05-14 12:43:01 +00001269 if( pInode->pNext ){
1270 assert( pInode->pNext->pPrev==pInode );
1271 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001272 }
drh8af6c222010-05-14 12:43:01 +00001273 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001274 }
drhbbd42a62004-05-22 17:41:58 +00001275 }
drhc68886b2017-08-18 16:09:52 +00001276 assert( inodeList!=0 || nUnusedFd==0 );
drhbbd42a62004-05-22 17:41:58 +00001277}
1278
1279/*
drh8af6c222010-05-14 12:43:01 +00001280** Given a file descriptor, locate the unixInodeInfo object that
1281** describes that file descriptor. Create a new one if necessary. The
1282** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001283**
dan9359c7b2009-08-21 08:29:10 +00001284** The mutex entered using the unixEnterMutex() function must be held
1285** when this function is called.
1286**
drh6c7d5c52008-11-21 20:32:33 +00001287** Return an appropriate error code.
1288*/
drh8af6c222010-05-14 12:43:01 +00001289static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001290 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001291 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001292){
1293 int rc; /* System call return code */
1294 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001295 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1296 struct stat statbuf; /* Low-level file information */
1297 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001298
dan9359c7b2009-08-21 08:29:10 +00001299 assert( unixMutexHeld() );
1300
drh6c7d5c52008-11-21 20:32:33 +00001301 /* Get low-level information about the file that we can used to
1302 ** create a unique name for the file.
1303 */
1304 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001305 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001306 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001307 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001308#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001309 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1310#endif
1311 return SQLITE_IOERR;
1312 }
1313
drheb0d74f2009-02-03 15:27:02 +00001314#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001315 /* On OS X on an msdos filesystem, the inode number is reported
1316 ** incorrectly for zero-size files. See ticket #3260. To work
1317 ** around this problem (we consider it a bug in OS X, not SQLite)
1318 ** we always increase the file size to 1 by writing a single byte
1319 ** prior to accessing the inode number. The one byte written is
1320 ** an ASCII 'S' character which also happens to be the first byte
1321 ** in the header of every SQLite database. In this way, if there
1322 ** is a race condition such that another thread has already populated
1323 ** the first page of the database, no damage is done.
1324 */
drh7ed97b92010-01-20 13:07:21 +00001325 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001326 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001327 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001328 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001329 return SQLITE_IOERR;
1330 }
drh99ab3b12011-03-02 15:09:07 +00001331 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001332 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001333 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001334 return SQLITE_IOERR;
1335 }
1336 }
drheb0d74f2009-02-03 15:27:02 +00001337#endif
drh6c7d5c52008-11-21 20:32:33 +00001338
drh8af6c222010-05-14 12:43:01 +00001339 memset(&fileId, 0, sizeof(fileId));
1340 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001341#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001342 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001343#else
drh25ef7f52016-12-05 20:06:45 +00001344 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001345#endif
drhc68886b2017-08-18 16:09:52 +00001346 assert( inodeList!=0 || nUnusedFd==0 );
drh8af6c222010-05-14 12:43:01 +00001347 pInode = inodeList;
1348 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1349 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001350 }
drh8af6c222010-05-14 12:43:01 +00001351 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001352 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001353 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001354 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001355 }
drh8af6c222010-05-14 12:43:01 +00001356 memset(pInode, 0, sizeof(*pInode));
1357 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1358 pInode->nRef = 1;
1359 pInode->pNext = inodeList;
1360 pInode->pPrev = 0;
1361 if( inodeList ) inodeList->pPrev = pInode;
1362 inodeList = pInode;
1363 }else{
1364 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001365 }
drh8af6c222010-05-14 12:43:01 +00001366 *ppInode = pInode;
1367 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001368}
drh6c7d5c52008-11-21 20:32:33 +00001369
drhb959a012013-12-07 12:29:22 +00001370/*
1371** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1372*/
1373static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001374#if OS_VXWORKS
1375 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1376#else
drhb959a012013-12-07 12:29:22 +00001377 struct stat buf;
1378 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001379 (osStat(pFile->zPath, &buf)!=0
1380 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001381#endif
drhb959a012013-12-07 12:29:22 +00001382}
1383
aswift5b1a2562008-08-22 00:22:35 +00001384
1385/*
drhfbc7e882013-04-11 01:16:15 +00001386** Check a unixFile that is a database. Verify the following:
1387**
1388** (1) There is exactly one hard link on the file
1389** (2) The file is not a symbolic link
1390** (3) The file has not been renamed or unlinked
1391**
1392** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1393*/
1394static void verifyDbFile(unixFile *pFile){
1395 struct stat buf;
1396 int rc;
drh86151e82015-12-08 14:37:16 +00001397
1398 /* These verifications occurs for the main database only */
1399 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1400
drhfbc7e882013-04-11 01:16:15 +00001401 rc = osFstat(pFile->h, &buf);
1402 if( rc!=0 ){
1403 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001404 return;
1405 }
drh6369bc32016-03-21 16:06:42 +00001406 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001407 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001408 return;
1409 }
1410 if( buf.st_nlink>1 ){
1411 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001412 return;
1413 }
drhb959a012013-12-07 12:29:22 +00001414 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001415 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001416 return;
1417 }
1418}
1419
1420
1421/*
danielk197713adf8a2004-06-03 16:08:41 +00001422** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001423** file by this or any other process. If such a lock is held, set *pResOut
1424** to a non-zero value otherwise *pResOut is set to zero. The return value
1425** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001426*/
danielk1977861f7452008-06-05 11:39:11 +00001427static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001428 int rc = SQLITE_OK;
1429 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001430 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001431
danielk1977861f7452008-06-05 11:39:11 +00001432 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1433
drh054889e2005-11-30 03:20:31 +00001434 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001435 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001436 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001437
1438 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001439 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001440 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001441 }
1442
drh2ac3ee92004-06-07 16:27:46 +00001443 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001444 */
danielk197709480a92009-02-09 05:32:32 +00001445#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001446 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001447 struct flock lock;
1448 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001449 lock.l_start = RESERVED_BYTE;
1450 lock.l_len = 1;
1451 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001452 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1453 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001454 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001455 } else if( lock.l_type!=F_UNLCK ){
1456 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001457 }
1458 }
danielk197709480a92009-02-09 05:32:32 +00001459#endif
danielk197713adf8a2004-06-03 16:08:41 +00001460
drh6c7d5c52008-11-21 20:32:33 +00001461 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001462 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001463
aswift5b1a2562008-08-22 00:22:35 +00001464 *pResOut = reserved;
1465 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001466}
1467
1468/*
drha7e61d82011-03-12 17:02:57 +00001469** Attempt to set a system-lock on the file pFile. The lock is
1470** described by pLock.
1471**
drh77197112011-03-15 19:08:48 +00001472** If the pFile was opened read/write from unix-excl, then the only lock
1473** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001474** the first time any lock is attempted. All subsequent system locking
1475** operations become no-ops. Locking operations still happen internally,
1476** in order to coordinate access between separate database connections
1477** within this process, but all of that is handled in memory and the
1478** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001479**
1480** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1481** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1482** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001483**
1484** Zero is returned if the call completes successfully, or -1 if a call
1485** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001486*/
1487static int unixFileLock(unixFile *pFile, struct flock *pLock){
1488 int rc;
drh3cb93392011-03-12 18:10:44 +00001489 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001490 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001491 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001492 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001493 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001494 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001495 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001496 lock.l_whence = SEEK_SET;
1497 lock.l_start = SHARED_FIRST;
1498 lock.l_len = SHARED_SIZE;
1499 lock.l_type = F_WRLCK;
1500 rc = osFcntl(pFile->h, F_SETLK, &lock);
1501 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001502 pInode->bProcessLock = 1;
1503 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001504 }else{
1505 rc = 0;
1506 }
1507 }else{
1508 rc = osFcntl(pFile->h, F_SETLK, pLock);
1509 }
1510 return rc;
1511}
1512
1513/*
drh308c2a52010-05-14 11:30:18 +00001514** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001515** of the following:
1516**
drh2ac3ee92004-06-07 16:27:46 +00001517** (1) SHARED_LOCK
1518** (2) RESERVED_LOCK
1519** (3) PENDING_LOCK
1520** (4) EXCLUSIVE_LOCK
1521**
drhb3e04342004-06-08 00:47:47 +00001522** Sometimes when requesting one lock state, additional lock states
1523** are inserted in between. The locking might fail on one of the later
1524** transitions leaving the lock state different from what it started but
1525** still short of its goal. The following chart shows the allowed
1526** transitions and the inserted intermediate states:
1527**
1528** UNLOCKED -> SHARED
1529** SHARED -> RESERVED
1530** SHARED -> (PENDING) -> EXCLUSIVE
1531** RESERVED -> (PENDING) -> EXCLUSIVE
1532** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001533**
drha6abd042004-06-09 17:37:22 +00001534** This routine will only increase a lock. Use the sqlite3OsUnlock()
1535** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001536*/
drh308c2a52010-05-14 11:30:18 +00001537static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001538 /* The following describes the implementation of the various locks and
1539 ** lock transitions in terms of the POSIX advisory shared and exclusive
1540 ** lock primitives (called read-locks and write-locks below, to avoid
1541 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001542 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001543 ** accessing the same database file, in case that is ever required.
1544 **
1545 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1546 ** byte', each single bytes at well known offsets, and the 'shared byte
1547 ** range', a range of 510 bytes at a well known offset.
1548 **
1549 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001550 ** byte'. If this is successful, 'shared byte range' is read-locked
1551 ** and the lock on the 'pending byte' released. (Legacy note: When
1552 ** SQLite was first developed, Windows95 systems were still very common,
1553 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1554 ** single randomly selected by from the 'shared byte range' is locked.
1555 ** Windows95 is now pretty much extinct, but this work-around for the
1556 ** lack of shared-locks on Windows95 lives on, for backwards
1557 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001558 **
danielk197790ba3bd2004-06-25 08:32:25 +00001559 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1560 ** A RESERVED lock is implemented by grabbing a write-lock on the
1561 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001562 **
1563 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001564 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1565 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1566 ** obtained, but existing SHARED locks are allowed to persist. A process
1567 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1568 ** This property is used by the algorithm for rolling back a journal file
1569 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001570 **
danielk197790ba3bd2004-06-25 08:32:25 +00001571 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1572 ** implemented by obtaining a write-lock on the entire 'shared byte
1573 ** range'. Since all other locks require a read-lock on one of the bytes
1574 ** within this range, this ensures that no other locks are held on the
1575 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001576 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001577 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001578 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001579 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001580 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001581 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001582
drh054889e2005-11-30 03:20:31 +00001583 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001584 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1585 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001586 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001587 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001588
1589 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001590 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001591 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001592 */
drh308c2a52010-05-14 11:30:18 +00001593 if( pFile->eFileLock>=eFileLock ){
1594 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1595 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001596 return SQLITE_OK;
1597 }
1598
drh0c2694b2009-09-03 16:23:44 +00001599 /* Make sure the locking sequence is correct.
1600 ** (1) We never move from unlocked to anything higher than shared lock.
1601 ** (2) SQLite never explicitly requests a pendig lock.
1602 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001603 */
drh308c2a52010-05-14 11:30:18 +00001604 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1605 assert( eFileLock!=PENDING_LOCK );
1606 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001607
drh8af6c222010-05-14 12:43:01 +00001608 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001609 */
drh6c7d5c52008-11-21 20:32:33 +00001610 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001611 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001612
danielk1977ad94b582007-08-20 06:44:22 +00001613 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001614 ** handle that precludes the requested lock, return BUSY.
1615 */
drh8af6c222010-05-14 12:43:01 +00001616 if( (pFile->eFileLock!=pInode->eFileLock &&
1617 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001618 ){
1619 rc = SQLITE_BUSY;
1620 goto end_lock;
1621 }
1622
1623 /* If a SHARED lock is requested, and some thread using this PID already
1624 ** has a SHARED or RESERVED lock, then increment reference counts and
1625 ** return SQLITE_OK.
1626 */
drh308c2a52010-05-14 11:30:18 +00001627 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001628 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001629 assert( eFileLock==SHARED_LOCK );
1630 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001631 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001632 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001633 pInode->nShared++;
1634 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001635 goto end_lock;
1636 }
1637
danielk19779a1d0ab2004-06-01 14:09:28 +00001638
drh3cde3bb2004-06-12 02:17:14 +00001639 /* A PENDING lock is needed before acquiring a SHARED lock and before
1640 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1641 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001642 */
drh0c2694b2009-09-03 16:23:44 +00001643 lock.l_len = 1L;
1644 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001645 if( eFileLock==SHARED_LOCK
1646 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001647 ){
drh308c2a52010-05-14 11:30:18 +00001648 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001649 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001650 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001651 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001652 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001653 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001654 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001655 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001656 goto end_lock;
1657 }
drh3cde3bb2004-06-12 02:17:14 +00001658 }
1659
1660
1661 /* If control gets to this point, then actually go ahead and make
1662 ** operating system calls for the specified lock.
1663 */
drh308c2a52010-05-14 11:30:18 +00001664 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001665 assert( pInode->nShared==0 );
1666 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001667 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001668
drh2ac3ee92004-06-07 16:27:46 +00001669 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001670 lock.l_start = SHARED_FIRST;
1671 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001672 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001673 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001674 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001675 }
dan661d71a2011-03-30 19:08:03 +00001676
drh2ac3ee92004-06-07 16:27:46 +00001677 /* Drop the temporary PENDING lock */
1678 lock.l_start = PENDING_BYTE;
1679 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001680 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001681 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1682 /* This could happen with a network mount */
1683 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001684 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001685 }
dan661d71a2011-03-30 19:08:03 +00001686
1687 if( rc ){
1688 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001689 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001690 }
dan661d71a2011-03-30 19:08:03 +00001691 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001692 }else{
drh308c2a52010-05-14 11:30:18 +00001693 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001694 pInode->nLock++;
1695 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001696 }
drh8af6c222010-05-14 12:43:01 +00001697 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001698 /* We are trying for an exclusive lock but another thread in this
1699 ** same process is still holding a shared lock. */
1700 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001701 }else{
drh3cde3bb2004-06-12 02:17:14 +00001702 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001703 ** assumed that there is a SHARED or greater lock on the file
1704 ** already.
1705 */
drh308c2a52010-05-14 11:30:18 +00001706 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001707 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001708
1709 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1710 if( eFileLock==RESERVED_LOCK ){
1711 lock.l_start = RESERVED_BYTE;
1712 lock.l_len = 1L;
1713 }else{
1714 lock.l_start = SHARED_FIRST;
1715 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001716 }
dan661d71a2011-03-30 19:08:03 +00001717
1718 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001719 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001720 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001721 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001722 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001723 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001724 }
drhbbd42a62004-05-22 17:41:58 +00001725 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001726
drh8f941bc2009-01-14 23:03:40 +00001727
drhd3d8c042012-05-29 17:02:40 +00001728#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001729 /* Set up the transaction-counter change checking flags when
1730 ** transitioning from a SHARED to a RESERVED lock. The change
1731 ** from SHARED to RESERVED marks the beginning of a normal
1732 ** write operation (not a hot journal rollback).
1733 */
1734 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001735 && pFile->eFileLock<=SHARED_LOCK
1736 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001737 ){
1738 pFile->transCntrChng = 0;
1739 pFile->dbUpdate = 0;
1740 pFile->inNormalWrite = 1;
1741 }
1742#endif
1743
1744
danielk1977ecb2a962004-06-02 06:30:16 +00001745 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001746 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001747 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001748 }else if( eFileLock==EXCLUSIVE_LOCK ){
1749 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001750 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001751 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001752
1753end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001754 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001755 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1756 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001757 return rc;
1758}
1759
1760/*
dan08da86a2009-08-21 17:18:03 +00001761** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001762** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001763*/
1764static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001765 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001766 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drh8af6c222010-05-14 12:43:01 +00001767 p->pNext = pInode->pUnused;
1768 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001769 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001770 pFile->pPreallocatedUnused = 0;
1771 nUnusedFd++;
dan08da86a2009-08-21 17:18:03 +00001772}
1773
1774/*
drh308c2a52010-05-14 11:30:18 +00001775** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001776** must be either NO_LOCK or SHARED_LOCK.
1777**
1778** If the locking level of the file descriptor is already at or below
1779** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001780**
1781** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1782** the byte range is divided into 2 parts and the first part is unlocked then
1783** set to a read lock, then the other part is simply unlocked. This works
1784** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1785** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001786*/
drha7e61d82011-03-12 17:02:57 +00001787static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001788 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001789 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001790 struct flock lock;
1791 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001792
drh054889e2005-11-30 03:20:31 +00001793 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001794 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001795 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001796 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001797
drh308c2a52010-05-14 11:30:18 +00001798 assert( eFileLock<=SHARED_LOCK );
1799 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001800 return SQLITE_OK;
1801 }
drh6c7d5c52008-11-21 20:32:33 +00001802 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001803 pInode = pFile->pInode;
1804 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001805 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001806 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001807
drhd3d8c042012-05-29 17:02:40 +00001808#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001809 /* When reducing a lock such that other processes can start
1810 ** reading the database file again, make sure that the
1811 ** transaction counter was updated if any part of the database
1812 ** file changed. If the transaction counter is not updated,
1813 ** other connections to the same file might not realize that
1814 ** the file has changed and hence might not know to flush their
1815 ** cache. The use of a stale cache can lead to database corruption.
1816 */
drh8f941bc2009-01-14 23:03:40 +00001817 pFile->inNormalWrite = 0;
1818#endif
1819
drh7ed97b92010-01-20 13:07:21 +00001820 /* downgrading to a shared lock on NFS involves clearing the write lock
1821 ** before establishing the readlock - to avoid a race condition we downgrade
1822 ** the lock in 2 blocks, so that part of the range will be covered by a
1823 ** write lock until the rest is covered by a read lock:
1824 ** 1: [WWWWW]
1825 ** 2: [....W]
1826 ** 3: [RRRRW]
1827 ** 4: [RRRR.]
1828 */
drh308c2a52010-05-14 11:30:18 +00001829 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001830#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001831 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001832 assert( handleNFSUnlock==0 );
1833#endif
1834#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001835 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001836 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001837 off_t divSize = SHARED_SIZE - 1;
1838
1839 lock.l_type = F_UNLCK;
1840 lock.l_whence = SEEK_SET;
1841 lock.l_start = SHARED_FIRST;
1842 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001843 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001844 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001845 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001846 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001847 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001848 }
drh7ed97b92010-01-20 13:07:21 +00001849 lock.l_type = F_RDLCK;
1850 lock.l_whence = SEEK_SET;
1851 lock.l_start = SHARED_FIRST;
1852 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001853 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001854 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001855 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1856 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001857 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001858 }
1859 goto end_unlock;
1860 }
1861 lock.l_type = F_UNLCK;
1862 lock.l_whence = SEEK_SET;
1863 lock.l_start = SHARED_FIRST+divSize;
1864 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001865 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001866 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001867 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001868 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001869 goto end_unlock;
1870 }
drh30f776f2011-02-25 03:25:07 +00001871 }else
1872#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1873 {
drh7ed97b92010-01-20 13:07:21 +00001874 lock.l_type = F_RDLCK;
1875 lock.l_whence = SEEK_SET;
1876 lock.l_start = SHARED_FIRST;
1877 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001878 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001879 /* In theory, the call to unixFileLock() cannot fail because another
1880 ** process is holding an incompatible lock. If it does, this
1881 ** indicates that the other process is not following the locking
1882 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1883 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1884 ** an assert to fail). */
1885 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001886 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001887 goto end_unlock;
1888 }
drh9c105bb2004-10-02 20:38:28 +00001889 }
1890 }
drhbbd42a62004-05-22 17:41:58 +00001891 lock.l_type = F_UNLCK;
1892 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001893 lock.l_start = PENDING_BYTE;
1894 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001895 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001896 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001897 }else{
danea83bc62011-04-01 11:56:32 +00001898 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001899 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001900 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001901 }
drhbbd42a62004-05-22 17:41:58 +00001902 }
drh308c2a52010-05-14 11:30:18 +00001903 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001904 /* Decrement the shared lock counter. Release the lock using an
1905 ** OS call only when all threads in this same process have released
1906 ** the lock.
1907 */
drh8af6c222010-05-14 12:43:01 +00001908 pInode->nShared--;
1909 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001910 lock.l_type = F_UNLCK;
1911 lock.l_whence = SEEK_SET;
1912 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001913 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001914 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001915 }else{
danea83bc62011-04-01 11:56:32 +00001916 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001917 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001918 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001919 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001920 }
drha6abd042004-06-09 17:37:22 +00001921 }
1922
drhbbd42a62004-05-22 17:41:58 +00001923 /* Decrement the count of locks against this same file. When the
1924 ** count reaches zero, close any other file descriptors whose close
1925 ** was deferred because of outstanding locks.
1926 */
drh8af6c222010-05-14 12:43:01 +00001927 pInode->nLock--;
1928 assert( pInode->nLock>=0 );
1929 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001930 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001931 }
1932 }
drhf2f105d2012-08-20 15:53:54 +00001933
aswift5b1a2562008-08-22 00:22:35 +00001934end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001935 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001936 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001937 return rc;
drhbbd42a62004-05-22 17:41:58 +00001938}
1939
1940/*
drh308c2a52010-05-14 11:30:18 +00001941** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001942** must be either NO_LOCK or SHARED_LOCK.
1943**
1944** If the locking level of the file descriptor is already at or below
1945** the requested locking level, this routine is a no-op.
1946*/
drh308c2a52010-05-14 11:30:18 +00001947static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001948#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001949 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001950#endif
drha7e61d82011-03-12 17:02:57 +00001951 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001952}
1953
mistachkine98844f2013-08-24 00:59:24 +00001954#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001955static int unixMapfile(unixFile *pFd, i64 nByte);
1956static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001957#endif
danf23da962013-03-23 21:00:41 +00001958
drh7ed97b92010-01-20 13:07:21 +00001959/*
danielk1977e339d652008-06-28 11:23:00 +00001960** This function performs the parts of the "close file" operation
1961** common to all locking schemes. It closes the directory and file
1962** handles, if they are valid, and sets all fields of the unixFile
1963** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001964**
1965** It is *not* necessary to hold the mutex when this routine is called,
1966** even on VxWorks. A mutex will be acquired on VxWorks by the
1967** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001968*/
1969static int closeUnixFile(sqlite3_file *id){
1970 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001971#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001972 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001973#endif
dan661d71a2011-03-30 19:08:03 +00001974 if( pFile->h>=0 ){
1975 robust_close(pFile, pFile->h, __LINE__);
1976 pFile->h = -1;
1977 }
1978#if OS_VXWORKS
1979 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001980 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001981 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001982 }
1983 vxworksReleaseFileId(pFile->pId);
1984 pFile->pId = 0;
1985 }
1986#endif
drh0bdbc902014-06-16 18:35:06 +00001987#ifdef SQLITE_UNLINK_AFTER_CLOSE
1988 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1989 osUnlink(pFile->zPath);
1990 sqlite3_free(*(char**)&pFile->zPath);
1991 pFile->zPath = 0;
1992 }
1993#endif
dan661d71a2011-03-30 19:08:03 +00001994 OSTRACE(("CLOSE %-3d\n", pFile->h));
1995 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00001996 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00001997 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001998 return SQLITE_OK;
1999}
2000
2001/*
danielk1977e3026632004-06-22 11:29:02 +00002002** Close a file.
2003*/
danielk197762079062007-08-15 17:08:46 +00002004static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002005 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002006 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00002007 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002008 unixUnlock(id, NO_LOCK);
2009 unixEnterMutex();
2010
2011 /* unixFile.pInode is always valid here. Otherwise, a different close
2012 ** routine (e.g. nolockClose()) would be called instead.
2013 */
2014 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2015 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
2016 /* If there are outstanding locks, do not actually close the file just
2017 ** yet because that would clear those locks. Instead, add the file
2018 ** descriptor to pInode->pUnused list. It will be automatically closed
2019 ** when the last lock is cleared.
2020 */
2021 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002022 }
dan661d71a2011-03-30 19:08:03 +00002023 releaseInodeInfo(pFile);
2024 rc = closeUnixFile(id);
2025 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002026 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002027}
2028
drh734c9862008-11-28 15:37:20 +00002029/************** End of the posix advisory lock implementation *****************
2030******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002031
drh734c9862008-11-28 15:37:20 +00002032/******************************************************************************
2033****************************** No-op Locking **********************************
2034**
2035** Of the various locking implementations available, this is by far the
2036** simplest: locking is ignored. No attempt is made to lock the database
2037** file for reading or writing.
2038**
2039** This locking mode is appropriate for use on read-only databases
2040** (ex: databases that are burned into CD-ROM, for example.) It can
2041** also be used if the application employs some external mechanism to
2042** prevent simultaneous access of the same database by two or more
2043** database connections. But there is a serious risk of database
2044** corruption if this locking mode is used in situations where multiple
2045** database connections are accessing the same database file at the same
2046** time and one or more of those connections are writing.
2047*/
drhbfe66312006-10-03 17:40:40 +00002048
drh734c9862008-11-28 15:37:20 +00002049static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2050 UNUSED_PARAMETER(NotUsed);
2051 *pResOut = 0;
2052 return SQLITE_OK;
2053}
drh734c9862008-11-28 15:37:20 +00002054static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2055 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2056 return SQLITE_OK;
2057}
drh734c9862008-11-28 15:37:20 +00002058static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2059 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2060 return SQLITE_OK;
2061}
2062
2063/*
drh9b35ea62008-11-29 02:20:26 +00002064** Close the file.
drh734c9862008-11-28 15:37:20 +00002065*/
2066static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002067 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002068}
2069
2070/******************* End of the no-op lock implementation *********************
2071******************************************************************************/
2072
2073/******************************************************************************
2074************************* Begin dot-file Locking ******************************
2075**
mistachkin48864df2013-03-21 21:20:32 +00002076** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002077** files (really a directory) to control access to the database. This works
2078** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002079**
2080** (1) There is zero concurrency. A single reader blocks all other
2081** connections from reading or writing the database.
2082**
2083** (2) An application crash or power loss can leave stale lock files
2084** sitting around that need to be cleared manually.
2085**
2086** Nevertheless, a dotlock is an appropriate locking mode for use if no
2087** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002088**
drh9ef6bc42011-11-04 02:24:02 +00002089** Dotfile locking works by creating a subdirectory in the same directory as
2090** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002091** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002092** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002093*/
2094
2095/*
2096** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002097** lock directory.
drh734c9862008-11-28 15:37:20 +00002098*/
2099#define DOTLOCK_SUFFIX ".lock"
2100
drh7708e972008-11-29 00:56:52 +00002101/*
2102** This routine checks if there is a RESERVED lock held on the specified
2103** file by this or any other process. If such a lock is held, set *pResOut
2104** to a non-zero value otherwise *pResOut is set to zero. The return value
2105** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2106**
2107** In dotfile locking, either a lock exists or it does not. So in this
2108** variation of CheckReservedLock(), *pResOut is set to true if any lock
2109** is held on the file and false if the file is unlocked.
2110*/
drh734c9862008-11-28 15:37:20 +00002111static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2112 int rc = SQLITE_OK;
2113 int reserved = 0;
2114 unixFile *pFile = (unixFile*)id;
2115
2116 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2117
2118 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002119 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002120 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002121 *pResOut = reserved;
2122 return rc;
2123}
2124
drh7708e972008-11-29 00:56:52 +00002125/*
drh308c2a52010-05-14 11:30:18 +00002126** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002127** of the following:
2128**
2129** (1) SHARED_LOCK
2130** (2) RESERVED_LOCK
2131** (3) PENDING_LOCK
2132** (4) EXCLUSIVE_LOCK
2133**
2134** Sometimes when requesting one lock state, additional lock states
2135** are inserted in between. The locking might fail on one of the later
2136** transitions leaving the lock state different from what it started but
2137** still short of its goal. The following chart shows the allowed
2138** transitions and the inserted intermediate states:
2139**
2140** UNLOCKED -> SHARED
2141** SHARED -> RESERVED
2142** SHARED -> (PENDING) -> EXCLUSIVE
2143** RESERVED -> (PENDING) -> EXCLUSIVE
2144** PENDING -> EXCLUSIVE
2145**
2146** This routine will only increase a lock. Use the sqlite3OsUnlock()
2147** routine to lower a locking level.
2148**
2149** With dotfile locking, we really only support state (4): EXCLUSIVE.
2150** But we track the other locking levels internally.
2151*/
drh308c2a52010-05-14 11:30:18 +00002152static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002153 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002154 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002155 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002156
drh7708e972008-11-29 00:56:52 +00002157
2158 /* If we have any lock, then the lock file already exists. All we have
2159 ** to do is adjust our internal record of the lock level.
2160 */
drh308c2a52010-05-14 11:30:18 +00002161 if( pFile->eFileLock > NO_LOCK ){
2162 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002163 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002164#ifdef HAVE_UTIME
2165 utime(zLockFile, NULL);
2166#else
drh734c9862008-11-28 15:37:20 +00002167 utimes(zLockFile, NULL);
2168#endif
drh7708e972008-11-29 00:56:52 +00002169 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002170 }
2171
2172 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002173 rc = osMkdir(zLockFile, 0777);
2174 if( rc<0 ){
2175 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002176 int tErrno = errno;
2177 if( EEXIST == tErrno ){
2178 rc = SQLITE_BUSY;
2179 } else {
2180 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002181 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002182 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002183 }
2184 }
drh7708e972008-11-29 00:56:52 +00002185 return rc;
drh734c9862008-11-28 15:37:20 +00002186 }
drh734c9862008-11-28 15:37:20 +00002187
2188 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002189 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002190 return rc;
2191}
2192
drh7708e972008-11-29 00:56:52 +00002193/*
drh308c2a52010-05-14 11:30:18 +00002194** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002195** must be either NO_LOCK or SHARED_LOCK.
2196**
2197** If the locking level of the file descriptor is already at or below
2198** the requested locking level, this routine is a no-op.
2199**
2200** When the locking level reaches NO_LOCK, delete the lock file.
2201*/
drh308c2a52010-05-14 11:30:18 +00002202static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002203 unixFile *pFile = (unixFile*)id;
2204 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002205 int rc;
drh734c9862008-11-28 15:37:20 +00002206
2207 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002208 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002209 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002210 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002211
2212 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002213 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002214 return SQLITE_OK;
2215 }
drh7708e972008-11-29 00:56:52 +00002216
2217 /* To downgrade to shared, simply update our internal notion of the
2218 ** lock state. No need to mess with the file on disk.
2219 */
drh308c2a52010-05-14 11:30:18 +00002220 if( eFileLock==SHARED_LOCK ){
2221 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002222 return SQLITE_OK;
2223 }
2224
drh7708e972008-11-29 00:56:52 +00002225 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002226 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002227 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002228 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002229 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002230 if( tErrno==ENOENT ){
2231 rc = SQLITE_OK;
2232 }else{
danea83bc62011-04-01 11:56:32 +00002233 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002234 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002235 }
2236 return rc;
2237 }
drh308c2a52010-05-14 11:30:18 +00002238 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002239 return SQLITE_OK;
2240}
2241
2242/*
drh9b35ea62008-11-29 02:20:26 +00002243** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002244*/
2245static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002246 unixFile *pFile = (unixFile*)id;
2247 assert( id!=0 );
2248 dotlockUnlock(id, NO_LOCK);
2249 sqlite3_free(pFile->lockingContext);
2250 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002251}
2252/****************** End of the dot-file lock implementation *******************
2253******************************************************************************/
2254
2255/******************************************************************************
2256************************** Begin flock Locking ********************************
2257**
2258** Use the flock() system call to do file locking.
2259**
drh6b9d6dd2008-12-03 19:34:47 +00002260** flock() locking is like dot-file locking in that the various
2261** fine-grain locking levels supported by SQLite are collapsed into
2262** a single exclusive lock. In other words, SHARED, RESERVED, and
2263** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2264** still works when you do this, but concurrency is reduced since
2265** only a single process can be reading the database at a time.
2266**
drhe89b2912015-03-03 20:42:01 +00002267** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002268*/
drhe89b2912015-03-03 20:42:01 +00002269#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002270
drh6b9d6dd2008-12-03 19:34:47 +00002271/*
drhff812312011-02-23 13:33:46 +00002272** Retry flock() calls that fail with EINTR
2273*/
2274#ifdef EINTR
2275static int robust_flock(int fd, int op){
2276 int rc;
2277 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2278 return rc;
2279}
2280#else
drh5c819272011-02-23 14:00:12 +00002281# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002282#endif
2283
2284
2285/*
drh6b9d6dd2008-12-03 19:34:47 +00002286** This routine checks if there is a RESERVED lock held on the specified
2287** file by this or any other process. If such a lock is held, set *pResOut
2288** to a non-zero value otherwise *pResOut is set to zero. The return value
2289** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2290*/
drh734c9862008-11-28 15:37:20 +00002291static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2292 int rc = SQLITE_OK;
2293 int reserved = 0;
2294 unixFile *pFile = (unixFile*)id;
2295
2296 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2297
2298 assert( pFile );
2299
2300 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002301 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002302 reserved = 1;
2303 }
2304
2305 /* Otherwise see if some other process holds it. */
2306 if( !reserved ){
2307 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002308 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002309 if( !lrc ){
2310 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002311 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002312 if ( lrc ) {
2313 int tErrno = errno;
2314 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002315 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002316 storeLastErrno(pFile, tErrno);
2317 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002318 }
2319 } else {
2320 int tErrno = errno;
2321 reserved = 1;
2322 /* someone else might have it reserved */
2323 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2324 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002325 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002326 rc = lrc;
2327 }
2328 }
2329 }
drh308c2a52010-05-14 11:30:18 +00002330 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002331
2332#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002333 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002334 rc = SQLITE_OK;
2335 reserved=1;
2336 }
2337#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2338 *pResOut = reserved;
2339 return rc;
2340}
2341
drh6b9d6dd2008-12-03 19:34:47 +00002342/*
drh308c2a52010-05-14 11:30:18 +00002343** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002344** of the following:
2345**
2346** (1) SHARED_LOCK
2347** (2) RESERVED_LOCK
2348** (3) PENDING_LOCK
2349** (4) EXCLUSIVE_LOCK
2350**
2351** Sometimes when requesting one lock state, additional lock states
2352** are inserted in between. The locking might fail on one of the later
2353** transitions leaving the lock state different from what it started but
2354** still short of its goal. The following chart shows the allowed
2355** transitions and the inserted intermediate states:
2356**
2357** UNLOCKED -> SHARED
2358** SHARED -> RESERVED
2359** SHARED -> (PENDING) -> EXCLUSIVE
2360** RESERVED -> (PENDING) -> EXCLUSIVE
2361** PENDING -> EXCLUSIVE
2362**
2363** flock() only really support EXCLUSIVE locks. We track intermediate
2364** lock states in the sqlite3_file structure, but all locks SHARED or
2365** above are really EXCLUSIVE locks and exclude all other processes from
2366** access the file.
2367**
2368** This routine will only increase a lock. Use the sqlite3OsUnlock()
2369** routine to lower a locking level.
2370*/
drh308c2a52010-05-14 11:30:18 +00002371static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002372 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002373 unixFile *pFile = (unixFile*)id;
2374
2375 assert( pFile );
2376
2377 /* if we already have a lock, it is exclusive.
2378 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002379 if (pFile->eFileLock > NO_LOCK) {
2380 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002381 return SQLITE_OK;
2382 }
2383
2384 /* grab an exclusive lock */
2385
drhff812312011-02-23 13:33:46 +00002386 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002387 int tErrno = errno;
2388 /* didn't get, must be busy */
2389 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2390 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002391 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002392 }
2393 } else {
2394 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002395 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002396 }
drh308c2a52010-05-14 11:30:18 +00002397 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2398 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002399#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002400 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002401 rc = SQLITE_BUSY;
2402 }
2403#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2404 return rc;
2405}
2406
drh6b9d6dd2008-12-03 19:34:47 +00002407
2408/*
drh308c2a52010-05-14 11:30:18 +00002409** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002410** must be either NO_LOCK or SHARED_LOCK.
2411**
2412** If the locking level of the file descriptor is already at or below
2413** the requested locking level, this routine is a no-op.
2414*/
drh308c2a52010-05-14 11:30:18 +00002415static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002416 unixFile *pFile = (unixFile*)id;
2417
2418 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002419 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002420 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002421 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002422
2423 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002424 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002425 return SQLITE_OK;
2426 }
2427
2428 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002429 if (eFileLock==SHARED_LOCK) {
2430 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002431 return SQLITE_OK;
2432 }
2433
2434 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002435 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002436#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002437 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002438#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002439 return SQLITE_IOERR_UNLOCK;
2440 }else{
drh308c2a52010-05-14 11:30:18 +00002441 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002442 return SQLITE_OK;
2443 }
2444}
2445
2446/*
2447** Close a file.
2448*/
2449static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002450 assert( id!=0 );
2451 flockUnlock(id, NO_LOCK);
2452 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002453}
2454
2455#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2456
2457/******************* End of the flock lock implementation *********************
2458******************************************************************************/
2459
2460/******************************************************************************
2461************************ Begin Named Semaphore Locking ************************
2462**
2463** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002464**
2465** Semaphore locking is like dot-lock and flock in that it really only
2466** supports EXCLUSIVE locking. Only a single process can read or write
2467** the database file at a time. This reduces potential concurrency, but
2468** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002469*/
2470#if OS_VXWORKS
2471
drh6b9d6dd2008-12-03 19:34:47 +00002472/*
2473** This routine checks if there is a RESERVED lock held on the specified
2474** file by this or any other process. If such a lock is held, set *pResOut
2475** to a non-zero value otherwise *pResOut is set to zero. The return value
2476** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2477*/
drh8cd5b252015-03-02 22:06:43 +00002478static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002479 int rc = SQLITE_OK;
2480 int reserved = 0;
2481 unixFile *pFile = (unixFile*)id;
2482
2483 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2484
2485 assert( pFile );
2486
2487 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002488 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002489 reserved = 1;
2490 }
2491
2492 /* Otherwise see if some other process holds it. */
2493 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002494 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002495
2496 if( sem_trywait(pSem)==-1 ){
2497 int tErrno = errno;
2498 if( EAGAIN != tErrno ){
2499 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002500 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002501 } else {
2502 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002503 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002504 }
2505 }else{
2506 /* we could have it if we want it */
2507 sem_post(pSem);
2508 }
2509 }
drh308c2a52010-05-14 11:30:18 +00002510 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002511
2512 *pResOut = reserved;
2513 return rc;
2514}
2515
drh6b9d6dd2008-12-03 19:34:47 +00002516/*
drh308c2a52010-05-14 11:30:18 +00002517** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002518** of the following:
2519**
2520** (1) SHARED_LOCK
2521** (2) RESERVED_LOCK
2522** (3) PENDING_LOCK
2523** (4) EXCLUSIVE_LOCK
2524**
2525** Sometimes when requesting one lock state, additional lock states
2526** are inserted in between. The locking might fail on one of the later
2527** transitions leaving the lock state different from what it started but
2528** still short of its goal. The following chart shows the allowed
2529** transitions and the inserted intermediate states:
2530**
2531** UNLOCKED -> SHARED
2532** SHARED -> RESERVED
2533** SHARED -> (PENDING) -> EXCLUSIVE
2534** RESERVED -> (PENDING) -> EXCLUSIVE
2535** PENDING -> EXCLUSIVE
2536**
2537** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2538** lock states in the sqlite3_file structure, but all locks SHARED or
2539** above are really EXCLUSIVE locks and exclude all other processes from
2540** access the file.
2541**
2542** This routine will only increase a lock. Use the sqlite3OsUnlock()
2543** routine to lower a locking level.
2544*/
drh8cd5b252015-03-02 22:06:43 +00002545static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002546 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002547 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002548 int rc = SQLITE_OK;
2549
2550 /* if we already have a lock, it is exclusive.
2551 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002552 if (pFile->eFileLock > NO_LOCK) {
2553 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002554 rc = SQLITE_OK;
2555 goto sem_end_lock;
2556 }
2557
2558 /* lock semaphore now but bail out when already locked. */
2559 if( sem_trywait(pSem)==-1 ){
2560 rc = SQLITE_BUSY;
2561 goto sem_end_lock;
2562 }
2563
2564 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002565 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002566
2567 sem_end_lock:
2568 return rc;
2569}
2570
drh6b9d6dd2008-12-03 19:34:47 +00002571/*
drh308c2a52010-05-14 11:30:18 +00002572** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002573** must be either NO_LOCK or SHARED_LOCK.
2574**
2575** If the locking level of the file descriptor is already at or below
2576** the requested locking level, this routine is a no-op.
2577*/
drh8cd5b252015-03-02 22:06:43 +00002578static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002579 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002580 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002581
2582 assert( pFile );
2583 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002584 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002585 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002586 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002587
2588 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002589 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002590 return SQLITE_OK;
2591 }
2592
2593 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002594 if (eFileLock==SHARED_LOCK) {
2595 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002596 return SQLITE_OK;
2597 }
2598
2599 /* no, really unlock. */
2600 if ( sem_post(pSem)==-1 ) {
2601 int rc, tErrno = errno;
2602 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2603 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002604 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002605 }
2606 return rc;
2607 }
drh308c2a52010-05-14 11:30:18 +00002608 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002609 return SQLITE_OK;
2610}
2611
2612/*
2613 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002614 */
drh8cd5b252015-03-02 22:06:43 +00002615static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002616 if( id ){
2617 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002618 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002619 assert( pFile );
2620 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002621 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002622 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002623 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002624 }
2625 return SQLITE_OK;
2626}
2627
2628#endif /* OS_VXWORKS */
2629/*
2630** Named semaphore locking is only available on VxWorks.
2631**
2632*************** End of the named semaphore lock implementation ****************
2633******************************************************************************/
2634
2635
2636/******************************************************************************
2637*************************** Begin AFP Locking *********************************
2638**
2639** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2640** on Apple Macintosh computers - both OS9 and OSX.
2641**
2642** Third-party implementations of AFP are available. But this code here
2643** only works on OSX.
2644*/
2645
drhd2cb50b2009-01-09 21:41:17 +00002646#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002647/*
2648** The afpLockingContext structure contains all afp lock specific state
2649*/
drhbfe66312006-10-03 17:40:40 +00002650typedef struct afpLockingContext afpLockingContext;
2651struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002652 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002653 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002654};
2655
2656struct ByteRangeLockPB2
2657{
2658 unsigned long long offset; /* offset to first byte to lock */
2659 unsigned long long length; /* nbr of bytes to lock */
2660 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2661 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2662 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2663 int fd; /* file desc to assoc this lock with */
2664};
2665
drhfd131da2007-08-07 17:13:03 +00002666#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002667
drh6b9d6dd2008-12-03 19:34:47 +00002668/*
2669** This is a utility for setting or clearing a bit-range lock on an
2670** AFP filesystem.
2671**
2672** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2673*/
2674static int afpSetLock(
2675 const char *path, /* Name of the file to be locked or unlocked */
2676 unixFile *pFile, /* Open file descriptor on path */
2677 unsigned long long offset, /* First byte to be locked */
2678 unsigned long long length, /* Number of bytes to lock */
2679 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002680){
drh6b9d6dd2008-12-03 19:34:47 +00002681 struct ByteRangeLockPB2 pb;
2682 int err;
drhbfe66312006-10-03 17:40:40 +00002683
2684 pb.unLockFlag = setLockFlag ? 0 : 1;
2685 pb.startEndFlag = 0;
2686 pb.offset = offset;
2687 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002688 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002689
drh308c2a52010-05-14 11:30:18 +00002690 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002691 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002692 offset, length));
drhbfe66312006-10-03 17:40:40 +00002693 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2694 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002695 int rc;
2696 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002697 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2698 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002699#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2700 rc = SQLITE_BUSY;
2701#else
drh734c9862008-11-28 15:37:20 +00002702 rc = sqliteErrorFromPosixError(tErrno,
2703 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002704#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002705 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002706 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002707 }
2708 return rc;
drhbfe66312006-10-03 17:40:40 +00002709 } else {
aswift5b1a2562008-08-22 00:22:35 +00002710 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002711 }
2712}
2713
drh6b9d6dd2008-12-03 19:34:47 +00002714/*
2715** This routine checks if there is a RESERVED lock held on the specified
2716** file by this or any other process. If such a lock is held, set *pResOut
2717** to a non-zero value otherwise *pResOut is set to zero. The return value
2718** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2719*/
danielk1977e339d652008-06-28 11:23:00 +00002720static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002721 int rc = SQLITE_OK;
2722 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002723 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002724 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002725
aswift5b1a2562008-08-22 00:22:35 +00002726 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2727
2728 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002729 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002730 if( context->reserved ){
2731 *pResOut = 1;
2732 return SQLITE_OK;
2733 }
drh8af6c222010-05-14 12:43:01 +00002734 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002735
2736 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002737 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002738 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002739 }
2740
2741 /* Otherwise see if some other process holds it.
2742 */
aswift5b1a2562008-08-22 00:22:35 +00002743 if( !reserved ){
2744 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002745 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002746 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002747 /* if we succeeded in taking the reserved lock, unlock it to restore
2748 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002749 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002750 } else {
2751 /* if we failed to get the lock then someone else must have it */
2752 reserved = 1;
2753 }
2754 if( IS_LOCK_ERROR(lrc) ){
2755 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002756 }
2757 }
drhbfe66312006-10-03 17:40:40 +00002758
drh7ed97b92010-01-20 13:07:21 +00002759 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002760 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002761
2762 *pResOut = reserved;
2763 return rc;
drhbfe66312006-10-03 17:40:40 +00002764}
2765
drh6b9d6dd2008-12-03 19:34:47 +00002766/*
drh308c2a52010-05-14 11:30:18 +00002767** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002768** of the following:
2769**
2770** (1) SHARED_LOCK
2771** (2) RESERVED_LOCK
2772** (3) PENDING_LOCK
2773** (4) EXCLUSIVE_LOCK
2774**
2775** Sometimes when requesting one lock state, additional lock states
2776** are inserted in between. The locking might fail on one of the later
2777** transitions leaving the lock state different from what it started but
2778** still short of its goal. The following chart shows the allowed
2779** transitions and the inserted intermediate states:
2780**
2781** UNLOCKED -> SHARED
2782** SHARED -> RESERVED
2783** SHARED -> (PENDING) -> EXCLUSIVE
2784** RESERVED -> (PENDING) -> EXCLUSIVE
2785** PENDING -> EXCLUSIVE
2786**
2787** This routine will only increase a lock. Use the sqlite3OsUnlock()
2788** routine to lower a locking level.
2789*/
drh308c2a52010-05-14 11:30:18 +00002790static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002791 int rc = SQLITE_OK;
2792 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002793 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002794 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002795
2796 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002797 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2798 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002799 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002800
drhbfe66312006-10-03 17:40:40 +00002801 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002802 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002803 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002804 */
drh308c2a52010-05-14 11:30:18 +00002805 if( pFile->eFileLock>=eFileLock ){
2806 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2807 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002808 return SQLITE_OK;
2809 }
2810
2811 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002812 ** (1) We never move from unlocked to anything higher than shared lock.
2813 ** (2) SQLite never explicitly requests a pendig lock.
2814 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002815 */
drh308c2a52010-05-14 11:30:18 +00002816 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2817 assert( eFileLock!=PENDING_LOCK );
2818 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002819
drh8af6c222010-05-14 12:43:01 +00002820 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002821 */
drh6c7d5c52008-11-21 20:32:33 +00002822 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002823 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002824
2825 /* If some thread using this PID has a lock via a different unixFile*
2826 ** handle that precludes the requested lock, return BUSY.
2827 */
drh8af6c222010-05-14 12:43:01 +00002828 if( (pFile->eFileLock!=pInode->eFileLock &&
2829 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002830 ){
2831 rc = SQLITE_BUSY;
2832 goto afp_end_lock;
2833 }
2834
2835 /* If a SHARED lock is requested, and some thread using this PID already
2836 ** has a SHARED or RESERVED lock, then increment reference counts and
2837 ** return SQLITE_OK.
2838 */
drh308c2a52010-05-14 11:30:18 +00002839 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002840 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002841 assert( eFileLock==SHARED_LOCK );
2842 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002843 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002844 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002845 pInode->nShared++;
2846 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002847 goto afp_end_lock;
2848 }
drhbfe66312006-10-03 17:40:40 +00002849
2850 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002851 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2852 ** be released.
2853 */
drh308c2a52010-05-14 11:30:18 +00002854 if( eFileLock==SHARED_LOCK
2855 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002856 ){
2857 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002858 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002859 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002860 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002861 goto afp_end_lock;
2862 }
2863 }
2864
2865 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002866 ** operating system calls for the specified lock.
2867 */
drh308c2a52010-05-14 11:30:18 +00002868 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002869 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002870 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002871
drh8af6c222010-05-14 12:43:01 +00002872 assert( pInode->nShared==0 );
2873 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002874
2875 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002876 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002877 /* note that the quality of the randomness doesn't matter that much */
2878 lk = random();
drh8af6c222010-05-14 12:43:01 +00002879 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002880 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002881 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002882 if( IS_LOCK_ERROR(lrc1) ){
2883 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002884 }
aswift5b1a2562008-08-22 00:22:35 +00002885 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002886 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002887
aswift5b1a2562008-08-22 00:22:35 +00002888 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002889 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002890 rc = lrc1;
2891 goto afp_end_lock;
2892 } else if( IS_LOCK_ERROR(lrc2) ){
2893 rc = lrc2;
2894 goto afp_end_lock;
2895 } else if( lrc1 != SQLITE_OK ) {
2896 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002897 } else {
drh308c2a52010-05-14 11:30:18 +00002898 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002899 pInode->nLock++;
2900 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002901 }
drh8af6c222010-05-14 12:43:01 +00002902 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002903 /* We are trying for an exclusive lock but another thread in this
2904 ** same process is still holding a shared lock. */
2905 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002906 }else{
2907 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2908 ** assumed that there is a SHARED or greater lock on the file
2909 ** already.
2910 */
2911 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002912 assert( 0!=pFile->eFileLock );
2913 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002914 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002915 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002916 if( !failed ){
2917 context->reserved = 1;
2918 }
drhbfe66312006-10-03 17:40:40 +00002919 }
drh308c2a52010-05-14 11:30:18 +00002920 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002921 /* Acquire an EXCLUSIVE lock */
2922
2923 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002924 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002925 */
drh6b9d6dd2008-12-03 19:34:47 +00002926 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002927 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002928 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002929 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002930 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002931 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002932 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002933 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002934 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2935 ** a critical I/O error
2936 */
drh2e233812017-08-22 15:21:54 +00002937 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00002938 SQLITE_IOERR_LOCK;
2939 goto afp_end_lock;
2940 }
2941 }else{
aswift5b1a2562008-08-22 00:22:35 +00002942 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002943 }
2944 }
aswift5b1a2562008-08-22 00:22:35 +00002945 if( failed ){
2946 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002947 }
2948 }
2949
2950 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002951 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002952 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002953 }else if( eFileLock==EXCLUSIVE_LOCK ){
2954 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002955 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002956 }
2957
2958afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002959 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002960 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2961 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002962 return rc;
2963}
2964
2965/*
drh308c2a52010-05-14 11:30:18 +00002966** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002967** must be either NO_LOCK or SHARED_LOCK.
2968**
2969** If the locking level of the file descriptor is already at or below
2970** the requested locking level, this routine is a no-op.
2971*/
drh308c2a52010-05-14 11:30:18 +00002972static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002973 int rc = SQLITE_OK;
2974 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002975 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002976 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2977 int skipShared = 0;
2978#ifdef SQLITE_TEST
2979 int h = pFile->h;
2980#endif
drhbfe66312006-10-03 17:40:40 +00002981
2982 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002983 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002984 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002985 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002986
drh308c2a52010-05-14 11:30:18 +00002987 assert( eFileLock<=SHARED_LOCK );
2988 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002989 return SQLITE_OK;
2990 }
drh6c7d5c52008-11-21 20:32:33 +00002991 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002992 pInode = pFile->pInode;
2993 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002994 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002995 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002996 SimulateIOErrorBenign(1);
2997 SimulateIOError( h=(-1) )
2998 SimulateIOErrorBenign(0);
2999
drhd3d8c042012-05-29 17:02:40 +00003000#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003001 /* When reducing a lock such that other processes can start
3002 ** reading the database file again, make sure that the
3003 ** transaction counter was updated if any part of the database
3004 ** file changed. If the transaction counter is not updated,
3005 ** other connections to the same file might not realize that
3006 ** the file has changed and hence might not know to flush their
3007 ** cache. The use of a stale cache can lead to database corruption.
3008 */
3009 assert( pFile->inNormalWrite==0
3010 || pFile->dbUpdate==0
3011 || pFile->transCntrChng==1 );
3012 pFile->inNormalWrite = 0;
3013#endif
aswiftaebf4132008-11-21 00:10:35 +00003014
drh308c2a52010-05-14 11:30:18 +00003015 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003016 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003017 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003018 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003019 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003020 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3021 } else {
3022 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003023 }
3024 }
drh308c2a52010-05-14 11:30:18 +00003025 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003026 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003027 }
drh308c2a52010-05-14 11:30:18 +00003028 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003029 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3030 if( !rc ){
3031 context->reserved = 0;
3032 }
aswiftaebf4132008-11-21 00:10:35 +00003033 }
drh8af6c222010-05-14 12:43:01 +00003034 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3035 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003036 }
aswiftaebf4132008-11-21 00:10:35 +00003037 }
drh308c2a52010-05-14 11:30:18 +00003038 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003039
drh7ed97b92010-01-20 13:07:21 +00003040 /* Decrement the shared lock counter. Release the lock using an
3041 ** OS call only when all threads in this same process have released
3042 ** the lock.
3043 */
drh8af6c222010-05-14 12:43:01 +00003044 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3045 pInode->nShared--;
3046 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003047 SimulateIOErrorBenign(1);
3048 SimulateIOError( h=(-1) )
3049 SimulateIOErrorBenign(0);
3050 if( !skipShared ){
3051 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3052 }
3053 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003054 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003055 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003056 }
3057 }
3058 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003059 pInode->nLock--;
3060 assert( pInode->nLock>=0 );
3061 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003062 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003063 }
3064 }
drhbfe66312006-10-03 17:40:40 +00003065 }
drh7ed97b92010-01-20 13:07:21 +00003066
drh6c7d5c52008-11-21 20:32:33 +00003067 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003068 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003069 return rc;
3070}
3071
3072/*
drh339eb0b2008-03-07 15:34:11 +00003073** Close a file & cleanup AFP specific locking context
3074*/
danielk1977e339d652008-06-28 11:23:00 +00003075static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003076 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003077 unixFile *pFile = (unixFile*)id;
3078 assert( id!=0 );
3079 afpUnlock(id, NO_LOCK);
3080 unixEnterMutex();
3081 if( pFile->pInode && pFile->pInode->nLock ){
3082 /* If there are outstanding locks, do not actually close the file just
3083 ** yet because that would clear those locks. Instead, add the file
3084 ** descriptor to pInode->aPending. It will be automatically closed when
3085 ** the last lock is cleared.
3086 */
3087 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003088 }
drha8de1e12015-11-30 00:05:39 +00003089 releaseInodeInfo(pFile);
3090 sqlite3_free(pFile->lockingContext);
3091 rc = closeUnixFile(id);
3092 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003093 return rc;
drhbfe66312006-10-03 17:40:40 +00003094}
3095
drhd2cb50b2009-01-09 21:41:17 +00003096#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003097/*
3098** The code above is the AFP lock implementation. The code is specific
3099** to MacOSX and does not work on other unix platforms. No alternative
3100** is available. If you don't compile for a mac, then the "unix-afp"
3101** VFS is not available.
3102**
3103********************* End of the AFP lock implementation **********************
3104******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003105
drh7ed97b92010-01-20 13:07:21 +00003106/******************************************************************************
3107*************************** Begin NFS Locking ********************************/
3108
3109#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3110/*
drh308c2a52010-05-14 11:30:18 +00003111 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003112 ** must be either NO_LOCK or SHARED_LOCK.
3113 **
3114 ** If the locking level of the file descriptor is already at or below
3115 ** the requested locking level, this routine is a no-op.
3116 */
drh308c2a52010-05-14 11:30:18 +00003117static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003118 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003119}
3120
3121#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3122/*
3123** The code above is the NFS lock implementation. The code is specific
3124** to MacOSX and does not work on other unix platforms. No alternative
3125** is available.
3126**
3127********************* End of the NFS lock implementation **********************
3128******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003129
3130/******************************************************************************
3131**************** Non-locking sqlite3_file methods *****************************
3132**
3133** The next division contains implementations for all methods of the
3134** sqlite3_file object other than the locking methods. The locking
3135** methods were defined in divisions above (one locking method per
3136** division). Those methods that are common to all locking modes
3137** are gather together into this division.
3138*/
drhbfe66312006-10-03 17:40:40 +00003139
3140/*
drh734c9862008-11-28 15:37:20 +00003141** Seek to the offset passed as the second argument, then read cnt
3142** bytes into pBuf. Return the number of bytes actually read.
3143**
3144** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3145** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3146** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003147** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003148** See tickets #2741 and #2681.
3149**
3150** To avoid stomping the errno value on a failed read the lastErrno value
3151** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003152*/
drh734c9862008-11-28 15:37:20 +00003153static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3154 int got;
drh58024642011-11-07 18:16:00 +00003155 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003156#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3157 i64 newOffset;
3158#endif
drh734c9862008-11-28 15:37:20 +00003159 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003160 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003161 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003162 do{
drh734c9862008-11-28 15:37:20 +00003163#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003164 got = osPread(id->h, pBuf, cnt, offset);
3165 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003166#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003167 got = osPread64(id->h, pBuf, cnt, offset);
3168 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003169#else
drha46cadc2016-03-04 03:02:06 +00003170 newOffset = lseek(id->h, offset, SEEK_SET);
3171 SimulateIOError( newOffset = -1 );
3172 if( newOffset<0 ){
3173 storeLastErrno((unixFile*)id, errno);
3174 return -1;
3175 }
3176 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003177#endif
drh58024642011-11-07 18:16:00 +00003178 if( got==cnt ) break;
3179 if( got<0 ){
3180 if( errno==EINTR ){ got = 1; continue; }
3181 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003182 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003183 break;
3184 }else if( got>0 ){
3185 cnt -= got;
3186 offset += got;
3187 prior += got;
3188 pBuf = (void*)(got + (char*)pBuf);
3189 }
3190 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003191 TIMER_END;
drh58024642011-11-07 18:16:00 +00003192 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3193 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3194 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003195}
3196
3197/*
drh734c9862008-11-28 15:37:20 +00003198** Read data from a file into a buffer. Return SQLITE_OK if all
3199** bytes were read successfully and SQLITE_IOERR if anything goes
3200** wrong.
drh339eb0b2008-03-07 15:34:11 +00003201*/
drh734c9862008-11-28 15:37:20 +00003202static int unixRead(
3203 sqlite3_file *id,
3204 void *pBuf,
3205 int amt,
3206 sqlite3_int64 offset
3207){
dan08da86a2009-08-21 17:18:03 +00003208 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003209 int got;
3210 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003211 assert( offset>=0 );
3212 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003213
dan08da86a2009-08-21 17:18:03 +00003214 /* If this is a database file (not a journal, master-journal or temp
3215 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003216#if 0
drhc68886b2017-08-18 16:09:52 +00003217 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003218 || offset>=PENDING_BYTE+512
3219 || offset+amt<=PENDING_BYTE
3220 );
dan7c246102010-04-12 19:00:29 +00003221#endif
drh08c6d442009-02-09 17:34:07 +00003222
drh9b4c59f2013-04-15 17:03:42 +00003223#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003224 /* Deal with as much of this read request as possible by transfering
3225 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003226 if( offset<pFile->mmapSize ){
3227 if( offset+amt <= pFile->mmapSize ){
3228 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3229 return SQLITE_OK;
3230 }else{
3231 int nCopy = pFile->mmapSize - offset;
3232 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3233 pBuf = &((u8 *)pBuf)[nCopy];
3234 amt -= nCopy;
3235 offset += nCopy;
3236 }
3237 }
drh6e0b6d52013-04-09 16:19:20 +00003238#endif
danf23da962013-03-23 21:00:41 +00003239
dan08da86a2009-08-21 17:18:03 +00003240 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003241 if( got==amt ){
3242 return SQLITE_OK;
3243 }else if( got<0 ){
3244 /* lastErrno set by seekAndRead */
3245 return SQLITE_IOERR_READ;
3246 }else{
drh4bf66fd2015-02-19 02:43:02 +00003247 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003248 /* Unread parts of the buffer must be zero-filled */
3249 memset(&((char*)pBuf)[got], 0, amt-got);
3250 return SQLITE_IOERR_SHORT_READ;
3251 }
3252}
3253
3254/*
dan47a2b4a2013-04-26 16:09:29 +00003255** Attempt to seek the file-descriptor passed as the first argument to
3256** absolute offset iOff, then attempt to write nBuf bytes of data from
3257** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3258** return the actual number of bytes written (which may be less than
3259** nBuf).
3260*/
3261static int seekAndWriteFd(
3262 int fd, /* File descriptor to write to */
3263 i64 iOff, /* File offset to begin writing at */
3264 const void *pBuf, /* Copy data from this buffer to the file */
3265 int nBuf, /* Size of buffer pBuf in bytes */
3266 int *piErrno /* OUT: Error number if error occurs */
3267){
3268 int rc = 0; /* Value returned by system call */
3269
3270 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003271 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003272 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003273 nBuf &= 0x1ffff;
3274 TIMER_START;
3275
3276#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003277 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003278#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003279 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003280#else
3281 do{
3282 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003283 SimulateIOError( iSeek = -1 );
3284 if( iSeek<0 ){
3285 rc = -1;
3286 break;
dan47a2b4a2013-04-26 16:09:29 +00003287 }
3288 rc = osWrite(fd, pBuf, nBuf);
3289 }while( rc<0 && errno==EINTR );
3290#endif
3291
3292 TIMER_END;
3293 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3294
drhe1818ec2015-12-01 16:21:35 +00003295 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003296 return rc;
3297}
3298
3299
3300/*
drh734c9862008-11-28 15:37:20 +00003301** Seek to the offset in id->offset then read cnt bytes into pBuf.
3302** Return the number of bytes actually read. Update the offset.
3303**
3304** To avoid stomping the errno value on a failed write the lastErrno value
3305** is set before returning.
3306*/
3307static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003308 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003309}
3310
3311
3312/*
3313** Write data from a buffer into a file. Return SQLITE_OK on success
3314** or some other error code on failure.
3315*/
3316static int unixWrite(
3317 sqlite3_file *id,
3318 const void *pBuf,
3319 int amt,
3320 sqlite3_int64 offset
3321){
dan08da86a2009-08-21 17:18:03 +00003322 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003323 int wrote = 0;
3324 assert( id );
3325 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003326
dan08da86a2009-08-21 17:18:03 +00003327 /* If this is a database file (not a journal, master-journal or temp
3328 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003329#if 0
drhc68886b2017-08-18 16:09:52 +00003330 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003331 || offset>=PENDING_BYTE+512
3332 || offset+amt<=PENDING_BYTE
3333 );
dan7c246102010-04-12 19:00:29 +00003334#endif
drh08c6d442009-02-09 17:34:07 +00003335
drhd3d8c042012-05-29 17:02:40 +00003336#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003337 /* If we are doing a normal write to a database file (as opposed to
3338 ** doing a hot-journal rollback or a write to some file other than a
3339 ** normal database file) then record the fact that the database
3340 ** has changed. If the transaction counter is modified, record that
3341 ** fact too.
3342 */
dan08da86a2009-08-21 17:18:03 +00003343 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003344 pFile->dbUpdate = 1; /* The database has been modified */
3345 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003346 int rc;
drh8f941bc2009-01-14 23:03:40 +00003347 char oldCntr[4];
3348 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003349 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003350 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003351 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003352 pFile->transCntrChng = 1; /* The transaction counter has changed */
3353 }
3354 }
3355 }
3356#endif
3357
danfe33e392015-11-17 20:56:06 +00003358#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003359 /* Deal with as much of this write request as possible by transfering
3360 ** data from the memory mapping using memcpy(). */
3361 if( offset<pFile->mmapSize ){
3362 if( offset+amt <= pFile->mmapSize ){
3363 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3364 return SQLITE_OK;
3365 }else{
3366 int nCopy = pFile->mmapSize - offset;
3367 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3368 pBuf = &((u8 *)pBuf)[nCopy];
3369 amt -= nCopy;
3370 offset += nCopy;
3371 }
3372 }
drh6e0b6d52013-04-09 16:19:20 +00003373#endif
drh02bf8b42015-09-01 23:51:53 +00003374
3375 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003376 amt -= wrote;
3377 offset += wrote;
3378 pBuf = &((char*)pBuf)[wrote];
3379 }
3380 SimulateIOError(( wrote=(-1), amt=1 ));
3381 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003382
drh02bf8b42015-09-01 23:51:53 +00003383 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003384 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003385 /* lastErrno set by seekAndWrite */
3386 return SQLITE_IOERR_WRITE;
3387 }else{
drh4bf66fd2015-02-19 02:43:02 +00003388 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003389 return SQLITE_FULL;
3390 }
3391 }
dan6e09d692010-07-27 18:34:15 +00003392
drh734c9862008-11-28 15:37:20 +00003393 return SQLITE_OK;
3394}
3395
3396#ifdef SQLITE_TEST
3397/*
3398** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003399** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003400*/
3401int sqlite3_sync_count = 0;
3402int sqlite3_fullsync_count = 0;
3403#endif
3404
3405/*
drh89240432009-03-25 01:06:01 +00003406** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003407** Others do no. To be safe, we will stick with the (slightly slower)
3408** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003409** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003410*/
drhf7a4a1b2015-01-10 18:02:45 +00003411#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003412# define fdatasync fsync
3413#endif
3414
3415/*
3416** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3417** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3418** only available on Mac OS X. But that could change.
3419*/
3420#ifdef F_FULLFSYNC
3421# define HAVE_FULLFSYNC 1
3422#else
3423# define HAVE_FULLFSYNC 0
3424#endif
3425
3426
3427/*
3428** The fsync() system call does not work as advertised on many
3429** unix systems. The following procedure is an attempt to make
3430** it work better.
3431**
3432** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3433** for testing when we want to run through the test suite quickly.
3434** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3435** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3436** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003437**
3438** SQLite sets the dataOnly flag if the size of the file is unchanged.
3439** The idea behind dataOnly is that it should only write the file content
3440** to disk, not the inode. We only set dataOnly if the file size is
3441** unchanged since the file size is part of the inode. However,
3442** Ted Ts'o tells us that fdatasync() will also write the inode if the
3443** file size has changed. The only real difference between fdatasync()
3444** and fsync(), Ted tells us, is that fdatasync() will not flush the
3445** inode if the mtime or owner or other inode attributes have changed.
3446** We only care about the file size, not the other file attributes, so
3447** as far as SQLite is concerned, an fdatasync() is always adequate.
3448** So, we always use fdatasync() if it is available, regardless of
3449** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003450*/
3451static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003452 int rc;
drh734c9862008-11-28 15:37:20 +00003453
3454 /* The following "ifdef/elif/else/" block has the same structure as
3455 ** the one below. It is replicated here solely to avoid cluttering
3456 ** up the real code with the UNUSED_PARAMETER() macros.
3457 */
3458#ifdef SQLITE_NO_SYNC
3459 UNUSED_PARAMETER(fd);
3460 UNUSED_PARAMETER(fullSync);
3461 UNUSED_PARAMETER(dataOnly);
3462#elif HAVE_FULLFSYNC
3463 UNUSED_PARAMETER(dataOnly);
3464#else
3465 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003466 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003467#endif
3468
3469 /* Record the number of times that we do a normal fsync() and
3470 ** FULLSYNC. This is used during testing to verify that this procedure
3471 ** gets called with the correct arguments.
3472 */
3473#ifdef SQLITE_TEST
3474 if( fullSync ) sqlite3_fullsync_count++;
3475 sqlite3_sync_count++;
3476#endif
3477
3478 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003479 ** no-op. But go ahead and call fstat() to validate the file
3480 ** descriptor as we need a method to provoke a failure during
3481 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003482 */
3483#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003484 {
3485 struct stat buf;
3486 rc = osFstat(fd, &buf);
3487 }
drh734c9862008-11-28 15:37:20 +00003488#elif HAVE_FULLFSYNC
3489 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003490 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003491 }else{
3492 rc = 1;
3493 }
3494 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003495 ** It shouldn't be possible for fullfsync to fail on the local
3496 ** file system (on OSX), so failure indicates that FULLFSYNC
3497 ** isn't supported for this file system. So, attempt an fsync
3498 ** and (for now) ignore the overhead of a superfluous fcntl call.
3499 ** It'd be better to detect fullfsync support once and avoid
3500 ** the fcntl call every time sync is called.
3501 */
drh734c9862008-11-28 15:37:20 +00003502 if( rc ) rc = fsync(fd);
3503
drh7ed97b92010-01-20 13:07:21 +00003504#elif defined(__APPLE__)
3505 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3506 ** so currently we default to the macro that redefines fdatasync to fsync
3507 */
3508 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003509#else
drh0b647ff2009-03-21 14:41:04 +00003510 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003511#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003512 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003513 rc = fsync(fd);
3514 }
drh0b647ff2009-03-21 14:41:04 +00003515#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003516#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3517
3518 if( OS_VXWORKS && rc!= -1 ){
3519 rc = 0;
3520 }
chw97185482008-11-17 08:05:31 +00003521 return rc;
drhbfe66312006-10-03 17:40:40 +00003522}
3523
drh734c9862008-11-28 15:37:20 +00003524/*
drh0059eae2011-08-08 23:48:40 +00003525** Open a file descriptor to the directory containing file zFilename.
3526** If successful, *pFd is set to the opened file descriptor and
3527** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3528** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3529** value.
3530**
drh90315a22011-08-10 01:52:12 +00003531** The directory file descriptor is used for only one thing - to
3532** fsync() a directory to make sure file creation and deletion events
3533** are flushed to disk. Such fsyncs are not needed on newer
3534** journaling filesystems, but are required on older filesystems.
3535**
3536** This routine can be overridden using the xSetSysCall interface.
3537** The ability to override this routine was added in support of the
3538** chromium sandbox. Opening a directory is a security risk (we are
3539** told) so making it overrideable allows the chromium sandbox to
3540** replace this routine with a harmless no-op. To make this routine
3541** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3542** *pFd set to a negative number.
3543**
drh0059eae2011-08-08 23:48:40 +00003544** If SQLITE_OK is returned, the caller is responsible for closing
3545** the file descriptor *pFd using close().
3546*/
3547static int openDirectory(const char *zFilename, int *pFd){
3548 int ii;
3549 int fd = -1;
3550 char zDirname[MAX_PATHNAME+1];
3551
3552 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003553 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3554 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003555 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003556 }else{
3557 if( zDirname[0]!='/' ) zDirname[0] = '.';
3558 zDirname[1] = 0;
3559 }
3560 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3561 if( fd>=0 ){
3562 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003563 }
3564 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003565 if( fd>=0 ) return SQLITE_OK;
3566 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003567}
3568
3569/*
drh734c9862008-11-28 15:37:20 +00003570** Make sure all writes to a particular file are committed to disk.
3571**
3572** If dataOnly==0 then both the file itself and its metadata (file
3573** size, access time, etc) are synced. If dataOnly!=0 then only the
3574** file data is synced.
3575**
3576** Under Unix, also make sure that the directory entry for the file
3577** has been created by fsync-ing the directory that contains the file.
3578** If we do not do this and we encounter a power failure, the directory
3579** entry for the journal might not exist after we reboot. The next
3580** SQLite to access the file will not know that the journal exists (because
3581** the directory entry for the journal was never created) and the transaction
3582** will not roll back - possibly leading to database corruption.
3583*/
3584static int unixSync(sqlite3_file *id, int flags){
3585 int rc;
3586 unixFile *pFile = (unixFile*)id;
3587
3588 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3589 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3590
3591 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3592 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3593 || (flags&0x0F)==SQLITE_SYNC_FULL
3594 );
3595
3596 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3597 ** line is to test that doing so does not cause any problems.
3598 */
3599 SimulateDiskfullError( return SQLITE_FULL );
3600
3601 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003602 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003603 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3604 SimulateIOError( rc=1 );
3605 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003606 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003607 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003608 }
drh0059eae2011-08-08 23:48:40 +00003609
3610 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003611 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003612 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003613 */
3614 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3615 int dirfd;
3616 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003617 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003618 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003619 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003620 full_fsync(dirfd, 0, 0);
3621 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003622 }else{
3623 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003624 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003625 }
drh0059eae2011-08-08 23:48:40 +00003626 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003627 }
3628 return rc;
3629}
3630
3631/*
3632** Truncate an open file to a specified size
3633*/
3634static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003635 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003636 int rc;
dan6e09d692010-07-27 18:34:15 +00003637 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003638 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003639
3640 /* If the user has configured a chunk-size for this file, truncate the
3641 ** file so that it consists of an integer number of chunks (i.e. the
3642 ** actual file size after the operation may be larger than the requested
3643 ** size).
3644 */
drhb8af4b72012-04-05 20:04:39 +00003645 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003646 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3647 }
3648
dan2ee53412014-09-06 16:49:40 +00003649 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003650 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003651 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003652 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003653 }else{
drhd3d8c042012-05-29 17:02:40 +00003654#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003655 /* If we are doing a normal write to a database file (as opposed to
3656 ** doing a hot-journal rollback or a write to some file other than a
3657 ** normal database file) and we truncate the file to zero length,
3658 ** that effectively updates the change counter. This might happen
3659 ** when restoring a database using the backup API from a zero-length
3660 ** source.
3661 */
dan6e09d692010-07-27 18:34:15 +00003662 if( pFile->inNormalWrite && nByte==0 ){
3663 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003664 }
danf23da962013-03-23 21:00:41 +00003665#endif
danc0003312013-03-22 17:46:11 +00003666
mistachkine98844f2013-08-24 00:59:24 +00003667#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003668 /* If the file was just truncated to a size smaller than the currently
3669 ** mapped region, reduce the effective mapping size as well. SQLite will
3670 ** use read() and write() to access data beyond this point from now on.
3671 */
3672 if( nByte<pFile->mmapSize ){
3673 pFile->mmapSize = nByte;
3674 }
mistachkine98844f2013-08-24 00:59:24 +00003675#endif
drh3313b142009-11-06 04:13:18 +00003676
drh734c9862008-11-28 15:37:20 +00003677 return SQLITE_OK;
3678 }
3679}
3680
3681/*
3682** Determine the current size of a file in bytes
3683*/
3684static int unixFileSize(sqlite3_file *id, i64 *pSize){
3685 int rc;
3686 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003687 assert( id );
3688 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003689 SimulateIOError( rc=1 );
3690 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003691 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003692 return SQLITE_IOERR_FSTAT;
3693 }
3694 *pSize = buf.st_size;
3695
drh8af6c222010-05-14 12:43:01 +00003696 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003697 ** writes a single byte into that file in order to work around a bug
3698 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3699 ** layers, we need to report this file size as zero even though it is
3700 ** really 1. Ticket #3260.
3701 */
3702 if( *pSize==1 ) *pSize = 0;
3703
3704
3705 return SQLITE_OK;
3706}
3707
drhd2cb50b2009-01-09 21:41:17 +00003708#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003709/*
3710** Handler for proxy-locking file-control verbs. Defined below in the
3711** proxying locking division.
3712*/
3713static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003714#endif
drh715ff302008-12-03 22:32:44 +00003715
dan502019c2010-07-28 14:26:17 +00003716/*
3717** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003718** file-control operation. Enlarge the database to nBytes in size
3719** (rounded up to the next chunk-size). If the database is already
3720** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003721*/
3722static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003723 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003724 i64 nSize; /* Required file size */
3725 struct stat buf; /* Used to hold return values of fstat() */
3726
drh4bf66fd2015-02-19 02:43:02 +00003727 if( osFstat(pFile->h, &buf) ){
3728 return SQLITE_IOERR_FSTAT;
3729 }
dan502019c2010-07-28 14:26:17 +00003730
3731 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3732 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003733
dan502019c2010-07-28 14:26:17 +00003734#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003735 /* The code below is handling the return value of osFallocate()
3736 ** correctly. posix_fallocate() is defined to "returns zero on success,
3737 ** or an error number on failure". See the manpage for details. */
3738 int err;
drhff812312011-02-23 13:33:46 +00003739 do{
dan661d71a2011-03-30 19:08:03 +00003740 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3741 }while( err==EINTR );
3742 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003743#else
dan592bf7f2014-12-30 19:58:31 +00003744 /* If the OS does not have posix_fallocate(), fake it. Write a
3745 ** single byte to the last byte in each block that falls entirely
3746 ** within the extended region. Then, if required, a single byte
3747 ** at offset (nSize-1), to set the size of the file correctly.
3748 ** This is a similar technique to that used by glibc on systems
3749 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003750 */
3751 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003752 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003753 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003754
drh053378d2015-12-01 22:09:42 +00003755 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003756 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003757 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003758 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3759 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003760 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003761 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003762 }
dan502019c2010-07-28 14:26:17 +00003763#endif
3764 }
3765 }
3766
mistachkine98844f2013-08-24 00:59:24 +00003767#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003768 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003769 int rc;
3770 if( pFile->szChunk<=0 ){
3771 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003772 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003773 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3774 }
3775 }
3776
3777 rc = unixMapfile(pFile, nByte);
3778 return rc;
3779 }
mistachkine98844f2013-08-24 00:59:24 +00003780#endif
danf23da962013-03-23 21:00:41 +00003781
dan502019c2010-07-28 14:26:17 +00003782 return SQLITE_OK;
3783}
danielk1977ad94b582007-08-20 06:44:22 +00003784
danielk1977e3026632004-06-22 11:29:02 +00003785/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003786** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003787** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3788**
3789** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3790*/
3791static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3792 if( *pArg<0 ){
3793 *pArg = (pFile->ctrlFlags & mask)!=0;
3794 }else if( (*pArg)==0 ){
3795 pFile->ctrlFlags &= ~mask;
3796 }else{
3797 pFile->ctrlFlags |= mask;
3798 }
3799}
3800
drh696b33e2012-12-06 19:01:42 +00003801/* Forward declaration */
3802static int unixGetTempname(int nBuf, char *zBuf);
3803
drhf12b3f62011-12-21 14:42:29 +00003804/*
drh9e33c2c2007-08-31 18:34:59 +00003805** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003806*/
drhcc6bb3e2007-08-31 16:11:35 +00003807static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003808 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003809 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003810#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003811 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3812 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003813 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003814 }
3815 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3816 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003817 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003818 }
3819 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3820 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003821 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003822 }
drhd76dba72017-07-22 16:00:34 +00003823#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003824
drh9e33c2c2007-08-31 18:34:59 +00003825 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003826 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003827 return SQLITE_OK;
3828 }
drh4bf66fd2015-02-19 02:43:02 +00003829 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003830 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003831 return SQLITE_OK;
3832 }
dan6e09d692010-07-27 18:34:15 +00003833 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003834 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003835 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003836 }
drh9ff27ec2010-05-19 19:26:05 +00003837 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003838 int rc;
3839 SimulateIOErrorBenign(1);
3840 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3841 SimulateIOErrorBenign(0);
3842 return rc;
drhf0b190d2011-07-26 16:03:07 +00003843 }
3844 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003845 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3846 return SQLITE_OK;
3847 }
drhcb15f352011-12-23 01:04:17 +00003848 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3849 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003850 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003851 }
drhde60fc22011-12-14 17:53:36 +00003852 case SQLITE_FCNTL_VFSNAME: {
3853 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3854 return SQLITE_OK;
3855 }
drh696b33e2012-12-06 19:01:42 +00003856 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003857 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003858 if( zTFile ){
3859 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3860 *(char**)pArg = zTFile;
3861 }
3862 return SQLITE_OK;
3863 }
drhb959a012013-12-07 12:29:22 +00003864 case SQLITE_FCNTL_HAS_MOVED: {
3865 *(int*)pArg = fileHasMoved(pFile);
3866 return SQLITE_OK;
3867 }
mistachkine98844f2013-08-24 00:59:24 +00003868#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003869 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003870 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003871 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003872 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3873 newLimit = sqlite3GlobalConfig.mxMmap;
3874 }
dan43c1e622017-08-07 18:13:28 +00003875
3876 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00003877 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3878 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00003879 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00003880 newLimit = (newLimit & 0x7FFFFFFF);
3881 }
3882
drh9b4c59f2013-04-15 17:03:42 +00003883 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003884 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003885 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003886 if( pFile->mmapSize>0 ){
3887 unixUnmapfile(pFile);
3888 rc = unixMapfile(pFile, -1);
3889 }
danbcb8a862013-04-08 15:30:41 +00003890 }
drh34e258c2013-05-23 01:40:53 +00003891 return rc;
danb2d3de32013-03-14 18:34:37 +00003892 }
mistachkine98844f2013-08-24 00:59:24 +00003893#endif
drhd3d8c042012-05-29 17:02:40 +00003894#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003895 /* The pager calls this method to signal that it has done
3896 ** a rollback and that the database is therefore unchanged and
3897 ** it hence it is OK for the transaction change counter to be
3898 ** unchanged.
3899 */
3900 case SQLITE_FCNTL_DB_UNCHANGED: {
3901 ((unixFile*)id)->dbUpdate = 0;
3902 return SQLITE_OK;
3903 }
3904#endif
drhd2cb50b2009-01-09 21:41:17 +00003905#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003906 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3907 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003908 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003909 }
drhd2cb50b2009-01-09 21:41:17 +00003910#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003911 }
drh0b52b7d2011-01-26 19:46:22 +00003912 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003913}
3914
3915/*
danefe16972017-07-20 19:49:14 +00003916** If pFd->sectorSize is non-zero when this function is called, it is a
3917** no-op. Otherwise, the values of pFd->sectorSize and
3918** pFd->deviceCharacteristics are set according to the file-system
3919** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00003920**
danefe16972017-07-20 19:49:14 +00003921** There are two versions of this function. One for QNX and one for all
3922** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00003923*/
danefe16972017-07-20 19:49:14 +00003924#ifndef __QNXNTO__
3925static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00003926 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00003927 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00003928#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003929 int res;
dan9d709542017-07-21 21:06:24 +00003930 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00003931
danefe16972017-07-20 19:49:14 +00003932 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00003933 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
3934 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00003935 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00003936 }
drhd76dba72017-07-22 16:00:34 +00003937#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003938
3939 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3940 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3941 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3942 }
3943
3944 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3945 }
3946}
3947#else
drh537dddf2012-10-26 13:46:24 +00003948#include <sys/dcmd_blk.h>
3949#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00003950static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00003951 if( pFile->sectorSize == 0 ){
3952 struct statvfs fsInfo;
3953
3954 /* Set defaults for non-supported filesystems */
3955 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3956 pFile->deviceCharacteristics = 0;
3957 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00003958 return;
drh537dddf2012-10-26 13:46:24 +00003959 }
3960
3961 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3962 pFile->sectorSize = fsInfo.f_bsize;
3963 pFile->deviceCharacteristics =
3964 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3965 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3966 ** the write succeeds */
3967 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3968 ** so it is ordered */
3969 0;
3970 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3971 pFile->sectorSize = fsInfo.f_bsize;
3972 pFile->deviceCharacteristics =
3973 /* etfs cluster size writes are atomic */
3974 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3975 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3976 ** the write succeeds */
3977 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3978 ** so it is ordered */
3979 0;
3980 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3981 pFile->sectorSize = fsInfo.f_bsize;
3982 pFile->deviceCharacteristics =
3983 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3984 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3985 ** the write succeeds */
3986 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3987 ** so it is ordered */
3988 0;
3989 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3990 pFile->sectorSize = fsInfo.f_bsize;
3991 pFile->deviceCharacteristics =
3992 /* full bitset of atomics from max sector size and smaller */
3993 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3994 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3995 ** so it is ordered */
3996 0;
3997 }else if( strstr(fsInfo.f_basetype, "dos") ){
3998 pFile->sectorSize = fsInfo.f_bsize;
3999 pFile->deviceCharacteristics =
4000 /* full bitset of atomics from max sector size and smaller */
4001 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4002 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4003 ** so it is ordered */
4004 0;
4005 }else{
4006 pFile->deviceCharacteristics =
4007 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4008 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4009 ** the write succeeds */
4010 0;
4011 }
4012 }
4013 /* Last chance verification. If the sector size isn't a multiple of 512
4014 ** then it isn't valid.*/
4015 if( pFile->sectorSize % 512 != 0 ){
4016 pFile->deviceCharacteristics = 0;
4017 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4018 }
drh537dddf2012-10-26 13:46:24 +00004019}
danefe16972017-07-20 19:49:14 +00004020#endif
4021
4022/*
4023** Return the sector size in bytes of the underlying block device for
4024** the specified file. This is almost always 512 bytes, but may be
4025** larger for some devices.
4026**
4027** SQLite code assumes this function cannot fail. It also assumes that
4028** if two files are created in the same file-system directory (i.e.
4029** a database and its journal file) that the sector size will be the
4030** same for both.
4031*/
4032static int unixSectorSize(sqlite3_file *id){
4033 unixFile *pFd = (unixFile*)id;
4034 setDeviceCharacteristics(pFd);
4035 return pFd->sectorSize;
4036}
danielk1977a3d4c882007-03-23 10:08:38 +00004037
danielk197790949c22007-08-17 16:50:38 +00004038/*
drhf12b3f62011-12-21 14:42:29 +00004039** Return the device characteristics for the file.
4040**
drhcb15f352011-12-23 01:04:17 +00004041** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004042** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004043** file system does not always provide powersafe overwrites. (In other
4044** words, after a power-loss event, parts of the file that were never
4045** written might end up being altered.) However, non-PSOW behavior is very,
4046** very rare. And asserting PSOW makes a large reduction in the amount
4047** of required I/O for journaling, since a lot of padding is eliminated.
4048** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4049** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004050*/
drhf12b3f62011-12-21 14:42:29 +00004051static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004052 unixFile *pFd = (unixFile*)id;
4053 setDeviceCharacteristics(pFd);
4054 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004055}
4056
dan702eec12014-06-23 10:04:58 +00004057#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004058
dan702eec12014-06-23 10:04:58 +00004059/*
4060** Return the system page size.
4061**
4062** This function should not be called directly by other code in this file.
4063** Instead, it should be called via macro osGetpagesize().
4064*/
4065static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004066#if OS_VXWORKS
4067 return 1024;
4068#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004069 return getpagesize();
4070#else
4071 return (int)sysconf(_SC_PAGESIZE);
4072#endif
4073}
4074
4075#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4076
4077#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004078
4079/*
drhd91c68f2010-05-14 14:52:25 +00004080** Object used to represent an shared memory buffer.
4081**
4082** When multiple threads all reference the same wal-index, each thread
4083** has its own unixShm object, but they all point to a single instance
4084** of this unixShmNode object. In other words, each wal-index is opened
4085** only once per process.
4086**
4087** Each unixShmNode object is connected to a single unixInodeInfo object.
4088** We could coalesce this object into unixInodeInfo, but that would mean
4089** every open file that does not use shared memory (in other words, most
4090** open files) would have to carry around this extra information. So
4091** the unixInodeInfo object contains a pointer to this unixShmNode object
4092** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004093**
4094** unixMutexHeld() must be true when creating or destroying
4095** this object or while reading or writing the following fields:
4096**
4097** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004098**
4099** The following fields are read-only after the object is created:
4100**
4101** fid
4102** zFilename
4103**
drhd91c68f2010-05-14 14:52:25 +00004104** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004105** unixMutexHeld() is true when reading or writing any other field
4106** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004107*/
drhd91c68f2010-05-14 14:52:25 +00004108struct unixShmNode {
4109 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004110 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004111 char *zFilename; /* Name of the mmapped file */
4112 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004113 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004114 u16 nRegion; /* Size of array apRegion */
4115 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004116 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004117 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004118 int nRef; /* Number of unixShm objects pointing to this */
4119 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004120#ifdef SQLITE_DEBUG
4121 u8 exclMask; /* Mask of exclusive locks held */
4122 u8 sharedMask; /* Mask of shared locks held */
4123 u8 nextShmId; /* Next available unixShm.id value */
4124#endif
4125};
4126
4127/*
drhd9e5c4f2010-05-12 18:01:39 +00004128** Structure used internally by this VFS to record the state of an
4129** open shared memory connection.
4130**
drhd91c68f2010-05-14 14:52:25 +00004131** The following fields are initialized when this object is created and
4132** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004133**
drhd91c68f2010-05-14 14:52:25 +00004134** unixShm.pFile
4135** unixShm.id
4136**
4137** All other fields are read/write. The unixShm.pFile->mutex must be held
4138** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004139*/
4140struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004141 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4142 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004143 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004144 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004145 u16 sharedMask; /* Mask of shared locks held */
4146 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004147};
4148
4149/*
drhd9e5c4f2010-05-12 18:01:39 +00004150** Constants used for locking
4151*/
drhbd9676c2010-06-23 17:58:38 +00004152#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004153#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004154
drhd9e5c4f2010-05-12 18:01:39 +00004155/*
drh73b64e42010-05-30 19:55:15 +00004156** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004157**
4158** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4159** otherwise.
4160*/
4161static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004162 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004163 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004164 int ofst, /* First byte of the locking range */
4165 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004166){
drhbbf76ee2015-03-10 20:22:35 +00004167 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4168 struct flock f; /* The posix advisory locking structure */
4169 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004170
drhd91c68f2010-05-14 14:52:25 +00004171 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004172 pShmNode = pFile->pInode->pShmNode;
drh37874b52017-12-13 10:11:09 +00004173 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
drhd9e5c4f2010-05-12 18:01:39 +00004174
dan9181ae92017-10-26 17:05:22 +00004175 /* Shared locks never span more than one byte */
4176 assert( n==1 || lockType!=F_RDLCK );
4177
4178 /* Locks are within range */
4179 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4180
drh3cb93392011-03-12 18:10:44 +00004181 if( pShmNode->h>=0 ){
4182 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004183 f.l_type = lockType;
4184 f.l_whence = SEEK_SET;
4185 f.l_start = ofst;
4186 f.l_len = n;
drhdcfb9652015-12-02 00:05:26 +00004187 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004188 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4189 }
drhd9e5c4f2010-05-12 18:01:39 +00004190
4191 /* Update the global lock state and do debug tracing */
4192#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004193 { u16 mask;
4194 OSTRACE(("SHM-LOCK "));
4195 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4196 if( rc==SQLITE_OK ){
4197 if( lockType==F_UNLCK ){
4198 OSTRACE(("unlock %d ok", ofst));
4199 pShmNode->exclMask &= ~mask;
4200 pShmNode->sharedMask &= ~mask;
4201 }else if( lockType==F_RDLCK ){
4202 OSTRACE(("read-lock %d ok", ofst));
4203 pShmNode->exclMask &= ~mask;
4204 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004205 }else{
dan9181ae92017-10-26 17:05:22 +00004206 assert( lockType==F_WRLCK );
4207 OSTRACE(("write-lock %d ok", ofst));
4208 pShmNode->exclMask |= mask;
4209 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004210 }
dan9181ae92017-10-26 17:05:22 +00004211 }else{
4212 if( lockType==F_UNLCK ){
4213 OSTRACE(("unlock %d failed", ofst));
4214 }else if( lockType==F_RDLCK ){
4215 OSTRACE(("read-lock failed"));
4216 }else{
4217 assert( lockType==F_WRLCK );
4218 OSTRACE(("write-lock %d failed", ofst));
4219 }
4220 }
4221 OSTRACE((" - afterwards %03x,%03x\n",
4222 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004223 }
drhd9e5c4f2010-05-12 18:01:39 +00004224#endif
4225
4226 return rc;
4227}
4228
dan781e34c2014-03-20 08:59:47 +00004229/*
dan781e34c2014-03-20 08:59:47 +00004230** Return the minimum number of 32KB shm regions that should be mapped at
4231** a time, assuming that each mapping must be an integer multiple of the
4232** current system page-size.
4233**
4234** Usually, this is 1. The exception seems to be systems that are configured
4235** to use 64KB pages - in this case each mapping must cover at least two
4236** shm regions.
4237*/
4238static int unixShmRegionPerMap(void){
4239 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004240 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004241 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4242 if( pgsz<shmsz ) return 1;
4243 return pgsz/shmsz;
4244}
drhd9e5c4f2010-05-12 18:01:39 +00004245
4246/*
drhd91c68f2010-05-14 14:52:25 +00004247** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004248**
4249** This is not a VFS shared-memory method; it is a utility function called
4250** by VFS shared-memory methods.
4251*/
drhd91c68f2010-05-14 14:52:25 +00004252static void unixShmPurge(unixFile *pFd){
4253 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004254 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004255 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004256 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004257 int i;
drhd91c68f2010-05-14 14:52:25 +00004258 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004259 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004260 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004261 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004262 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004263 }else{
4264 sqlite3_free(p->apRegion[i]);
4265 }
dan13a3cb82010-06-11 19:04:21 +00004266 }
dan18801912010-06-14 14:07:50 +00004267 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004268 if( p->h>=0 ){
4269 robust_close(pFd, p->h, __LINE__);
4270 p->h = -1;
4271 }
drhd91c68f2010-05-14 14:52:25 +00004272 p->pInode->pShmNode = 0;
4273 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004274 }
4275}
4276
4277/*
dan92c02da2017-11-01 20:59:28 +00004278** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4279** take it now. Return SQLITE_OK if successful, or an SQLite error
4280** code otherwise.
4281**
4282** If the DMS cannot be locked because this is a readonly_shm=1
4283** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004284** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004285*/
4286static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4287 struct flock lock;
4288 int rc = SQLITE_OK;
4289
4290 /* Use F_GETLK to determine the locks other processes are holding
4291 ** on the DMS byte. If it indicates that another process is holding
4292 ** a SHARED lock, then this process may also take a SHARED lock
4293 ** and proceed with opening the *-shm file.
4294 **
4295 ** Or, if no other process is holding any lock, then this process
4296 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4297 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4298 ** downgrade to a SHARED lock on the DMS byte.
4299 **
4300 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4301 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4302 ** version of this code attempted the SHARED lock at this point. But
4303 ** this introduced a subtle race condition: if the process holding
4304 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4305 ** process might open and use the *-shm file without truncating it.
4306 ** And if the *-shm file has been corrupted by a power failure or
4307 ** system crash, the database itself may also become corrupt. */
4308 lock.l_whence = SEEK_SET;
4309 lock.l_start = UNIX_SHM_DMS;
4310 lock.l_len = 1;
4311 lock.l_type = F_WRLCK;
4312 if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
4313 rc = SQLITE_IOERR_LOCK;
4314 }else if( lock.l_type==F_UNLCK ){
4315 if( pShmNode->isReadonly ){
4316 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004317 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004318 }else{
4319 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4320 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
4321 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4322 }
4323 }
4324 }else if( lock.l_type==F_WRLCK ){
4325 rc = SQLITE_BUSY;
4326 }
4327
4328 if( rc==SQLITE_OK ){
4329 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4330 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4331 }
4332 return rc;
4333}
4334
4335/*
danda9fe0c2010-07-13 18:44:03 +00004336** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004337** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004338**
drh7234c6d2010-06-19 15:10:09 +00004339** The file used to implement shared-memory is in the same directory
4340** as the open database file and has the same name as the open database
4341** file with the "-shm" suffix added. For example, if the database file
4342** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004343** for shared memory will be called "/home/user1/config.db-shm".
4344**
4345** Another approach to is to use files in /dev/shm or /dev/tmp or an
4346** some other tmpfs mount. But if a file in a different directory
4347** from the database file is used, then differing access permissions
4348** or a chroot() might cause two different processes on the same
4349** database to end up using different files for shared memory -
4350** meaning that their memory would not really be shared - resulting
4351** in database corruption. Nevertheless, this tmpfs file usage
4352** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4353** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4354** option results in an incompatible build of SQLite; builds of SQLite
4355** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4356** same database file at the same time, database corruption will likely
4357** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4358** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004359**
4360** When opening a new shared-memory file, if no other instances of that
4361** file are currently open, in this process or in other processes, then
4362** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004363**
4364** If the original database file (pDbFd) is using the "unix-excl" VFS
4365** that means that an exclusive lock is held on the database file and
4366** that no other processes are able to read or write the database. In
4367** that case, we do not really need shared memory. No shared memory
4368** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004369*/
danda9fe0c2010-07-13 18:44:03 +00004370static int unixOpenSharedMemory(unixFile *pDbFd){
4371 struct unixShm *p = 0; /* The connection to be opened */
4372 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004373 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004374 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004375 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004376 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004377
danda9fe0c2010-07-13 18:44:03 +00004378 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004379 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004380 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004381 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004382 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004383
danda9fe0c2010-07-13 18:44:03 +00004384 /* Check to see if a unixShmNode object already exists. Reuse an existing
4385 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004386 */
4387 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004388 pInode = pDbFd->pInode;
4389 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004390 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004391 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004392#ifndef SQLITE_SHM_DIRECTORY
4393 const char *zBasePath = pDbFd->zPath;
4394#endif
danddb0ac42010-07-14 14:48:58 +00004395
4396 /* Call fstat() to figure out the permissions on the database file. If
4397 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004398 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004399 */
drhf3b1ed02015-12-02 13:11:03 +00004400 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004401 rc = SQLITE_IOERR_FSTAT;
4402 goto shm_open_err;
4403 }
4404
drha4ced192010-07-15 18:32:40 +00004405#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004406 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004407#else
drh4bf66fd2015-02-19 02:43:02 +00004408 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004409#endif
drhf3cdcdc2015-04-29 16:50:28 +00004410 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004411 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004412 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004413 goto shm_open_err;
4414 }
drh9cb5a0d2012-01-05 21:19:54 +00004415 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004416 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004417#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004418 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004419 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4420 (u32)sStat.st_ino, (u32)sStat.st_dev);
4421#else
danf12ba662017-11-07 15:43:52 +00004422 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4423 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004424#endif
drhd91c68f2010-05-14 14:52:25 +00004425 pShmNode->h = -1;
4426 pDbFd->pInode->pShmNode = pShmNode;
4427 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004428 if( sqlite3GlobalConfig.bCoreMutex ){
4429 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4430 if( pShmNode->mutex==0 ){
4431 rc = SQLITE_NOMEM_BKPT;
4432 goto shm_open_err;
4433 }
drhd91c68f2010-05-14 14:52:25 +00004434 }
drhd9e5c4f2010-05-12 18:01:39 +00004435
drh3cb93392011-03-12 18:10:44 +00004436 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004437 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4438 pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004439 }
drh3cb93392011-03-12 18:10:44 +00004440 if( pShmNode->h<0 ){
danf12ba662017-11-07 15:43:52 +00004441 pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
4442 if( pShmNode->h<0 ){
4443 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4444 goto shm_open_err;
4445 }
4446 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004447 }
drhac7c3ac2012-02-11 19:23:48 +00004448
4449 /* If this process is running as root, make sure that the SHM file
4450 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004451 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004452 */
drh6226ca22015-11-24 15:06:28 +00004453 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004454
dan92c02da2017-11-01 20:59:28 +00004455 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004456 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004457 }
drhd9e5c4f2010-05-12 18:01:39 +00004458 }
4459
drhd91c68f2010-05-14 14:52:25 +00004460 /* Make the new connection a child of the unixShmNode */
4461 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004462#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004463 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004464#endif
drhd91c68f2010-05-14 14:52:25 +00004465 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004466 pDbFd->pShm = p;
4467 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004468
4469 /* The reference count on pShmNode has already been incremented under
4470 ** the cover of the unixEnterMutex() mutex and the pointer from the
4471 ** new (struct unixShm) object to the pShmNode has been set. All that is
4472 ** left to do is to link the new object into the linked list starting
4473 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4474 ** mutex.
4475 */
4476 sqlite3_mutex_enter(pShmNode->mutex);
4477 p->pNext = pShmNode->pFirst;
4478 pShmNode->pFirst = p;
4479 sqlite3_mutex_leave(pShmNode->mutex);
dan92c02da2017-11-01 20:59:28 +00004480 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004481
4482 /* Jump here on any error */
4483shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004484 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004485 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004486 unixLeaveMutex();
4487 return rc;
4488}
4489
4490/*
danda9fe0c2010-07-13 18:44:03 +00004491** This function is called to obtain a pointer to region iRegion of the
4492** shared-memory associated with the database file fd. Shared-memory regions
4493** are numbered starting from zero. Each shared-memory region is szRegion
4494** bytes in size.
4495**
4496** If an error occurs, an error code is returned and *pp is set to NULL.
4497**
4498** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4499** region has not been allocated (by any client, including one running in a
4500** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4501** bExtend is non-zero and the requested shared-memory region has not yet
4502** been allocated, it is allocated by this function.
4503**
4504** If the shared-memory region has already been allocated or is allocated by
4505** this call as described above, then it is mapped into this processes
4506** address space (if it is not already), *pp is set to point to the mapped
4507** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004508*/
danda9fe0c2010-07-13 18:44:03 +00004509static int unixShmMap(
4510 sqlite3_file *fd, /* Handle open on database file */
4511 int iRegion, /* Region to retrieve */
4512 int szRegion, /* Size of regions */
4513 int bExtend, /* True to extend file if necessary */
4514 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004515){
danda9fe0c2010-07-13 18:44:03 +00004516 unixFile *pDbFd = (unixFile*)fd;
4517 unixShm *p;
4518 unixShmNode *pShmNode;
4519 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004520 int nShmPerMap = unixShmRegionPerMap();
4521 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004522
danda9fe0c2010-07-13 18:44:03 +00004523 /* If the shared-memory file has not yet been opened, open it now. */
4524 if( pDbFd->pShm==0 ){
4525 rc = unixOpenSharedMemory(pDbFd);
4526 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004527 }
drhd9e5c4f2010-05-12 18:01:39 +00004528
danda9fe0c2010-07-13 18:44:03 +00004529 p = pDbFd->pShm;
4530 pShmNode = p->pShmNode;
4531 sqlite3_mutex_enter(pShmNode->mutex);
dan92c02da2017-11-01 20:59:28 +00004532 if( pShmNode->isUnlocked ){
4533 rc = unixLockSharedMemory(pDbFd, pShmNode);
4534 if( rc!=SQLITE_OK ) goto shmpage_out;
4535 pShmNode->isUnlocked = 0;
4536 }
danda9fe0c2010-07-13 18:44:03 +00004537 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004538 assert( pShmNode->pInode==pDbFd->pInode );
4539 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4540 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004541
dan781e34c2014-03-20 08:59:47 +00004542 /* Minimum number of regions required to be mapped. */
4543 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4544
4545 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004546 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004547 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004548 struct stat sStat; /* Used by fstat() */
4549
4550 pShmNode->szRegion = szRegion;
4551
drh3cb93392011-03-12 18:10:44 +00004552 if( pShmNode->h>=0 ){
4553 /* The requested region is not mapped into this processes address space.
4554 ** Check to see if it has been allocated (i.e. if the wal-index file is
4555 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004556 */
drh3cb93392011-03-12 18:10:44 +00004557 if( osFstat(pShmNode->h, &sStat) ){
4558 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004559 goto shmpage_out;
4560 }
drh3cb93392011-03-12 18:10:44 +00004561
4562 if( sStat.st_size<nByte ){
4563 /* The requested memory region does not exist. If bExtend is set to
4564 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004565 */
dan47a2b4a2013-04-26 16:09:29 +00004566 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004567 goto shmpage_out;
4568 }
dan47a2b4a2013-04-26 16:09:29 +00004569
4570 /* Alternatively, if bExtend is true, extend the file. Do this by
4571 ** writing a single byte to the end of each (OS) page being
4572 ** allocated or extended. Technically, we need only write to the
4573 ** last page in order to extend the file. But writing to all new
4574 ** pages forces the OS to allocate them immediately, which reduces
4575 ** the chances of SIGBUS while accessing the mapped region later on.
4576 */
4577 else{
4578 static const int pgsz = 4096;
4579 int iPg;
4580
4581 /* Write to the last byte of each newly allocated or extended page */
4582 assert( (nByte % pgsz)==0 );
4583 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004584 int x = 0;
4585 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004586 const char *zFile = pShmNode->zFilename;
4587 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4588 goto shmpage_out;
4589 }
4590 }
drh3cb93392011-03-12 18:10:44 +00004591 }
4592 }
danda9fe0c2010-07-13 18:44:03 +00004593 }
4594
4595 /* Map the requested memory region into this processes address space. */
4596 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004597 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004598 );
4599 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004600 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004601 goto shmpage_out;
4602 }
4603 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004604 while( pShmNode->nRegion<nReqRegion ){
4605 int nMap = szRegion*nShmPerMap;
4606 int i;
drh3cb93392011-03-12 18:10:44 +00004607 void *pMem;
4608 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004609 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004610 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004611 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004612 );
4613 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004614 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004615 goto shmpage_out;
4616 }
4617 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004618 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004619 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004620 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004621 goto shmpage_out;
4622 }
4623 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004624 }
dan781e34c2014-03-20 08:59:47 +00004625
4626 for(i=0; i<nShmPerMap; i++){
4627 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4628 }
4629 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004630 }
4631 }
4632
4633shmpage_out:
4634 if( pShmNode->nRegion>iRegion ){
4635 *pp = pShmNode->apRegion[iRegion];
4636 }else{
4637 *pp = 0;
4638 }
drh66dfec8b2011-06-01 20:01:49 +00004639 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004640 sqlite3_mutex_leave(pShmNode->mutex);
4641 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004642}
4643
4644/*
drhd9e5c4f2010-05-12 18:01:39 +00004645** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004646**
4647** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4648** different here than in posix. In xShmLock(), one can go from unlocked
4649** to shared and back or from unlocked to exclusive and back. But one may
4650** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004651*/
4652static int unixShmLock(
4653 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004654 int ofst, /* First lock to acquire or release */
4655 int n, /* Number of locks to acquire or release */
4656 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004657){
drh73b64e42010-05-30 19:55:15 +00004658 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4659 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4660 unixShm *pX; /* For looping over all siblings */
4661 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4662 int rc = SQLITE_OK; /* Result code */
4663 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004664
drhd91c68f2010-05-14 14:52:25 +00004665 assert( pShmNode==pDbFd->pInode->pShmNode );
4666 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004667 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004668 assert( n>=1 );
4669 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4670 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4671 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4672 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4673 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004674 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4675 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004676
drhc99597c2010-05-31 01:41:15 +00004677 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004678 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004679 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004680 if( flags & SQLITE_SHM_UNLOCK ){
4681 u16 allMask = 0; /* Mask of locks held by siblings */
4682
4683 /* See if any siblings hold this same lock */
4684 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4685 if( pX==p ) continue;
4686 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4687 allMask |= pX->sharedMask;
4688 }
4689
4690 /* Unlock the system-level locks */
4691 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004692 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004693 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004694 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004695 }
drh73b64e42010-05-30 19:55:15 +00004696
4697 /* Undo the local locks */
4698 if( rc==SQLITE_OK ){
4699 p->exclMask &= ~mask;
4700 p->sharedMask &= ~mask;
4701 }
4702 }else if( flags & SQLITE_SHM_SHARED ){
4703 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4704
4705 /* Find out which shared locks are already held by sibling connections.
4706 ** If any sibling already holds an exclusive lock, go ahead and return
4707 ** SQLITE_BUSY.
4708 */
4709 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004710 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004711 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004712 break;
4713 }
4714 allShared |= pX->sharedMask;
4715 }
4716
4717 /* Get shared locks at the system level, if necessary */
4718 if( rc==SQLITE_OK ){
4719 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004720 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004721 }else{
drh73b64e42010-05-30 19:55:15 +00004722 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004723 }
drhd9e5c4f2010-05-12 18:01:39 +00004724 }
drh73b64e42010-05-30 19:55:15 +00004725
4726 /* Get the local shared locks */
4727 if( rc==SQLITE_OK ){
4728 p->sharedMask |= mask;
4729 }
4730 }else{
4731 /* Make sure no sibling connections hold locks that will block this
4732 ** lock. If any do, return SQLITE_BUSY right away.
4733 */
4734 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004735 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4736 rc = SQLITE_BUSY;
4737 break;
4738 }
4739 }
4740
4741 /* Get the exclusive locks at the system level. Then if successful
4742 ** also mark the local connection as being locked.
4743 */
4744 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004745 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004746 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004747 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004748 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004749 }
drhd9e5c4f2010-05-12 18:01:39 +00004750 }
4751 }
drhd91c68f2010-05-14 14:52:25 +00004752 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004753 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004754 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004755 return rc;
4756}
4757
drh286a2882010-05-20 23:51:06 +00004758/*
4759** Implement a memory barrier or memory fence on shared memory.
4760**
4761** All loads and stores begun before the barrier must complete before
4762** any load or store begun after the barrier.
4763*/
4764static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004765 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004766){
drhff828942010-06-26 21:34:06 +00004767 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004768 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4769 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004770 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004771}
4772
dan18801912010-06-14 14:07:50 +00004773/*
danda9fe0c2010-07-13 18:44:03 +00004774** Close a connection to shared-memory. Delete the underlying
4775** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004776**
4777** If there is no shared memory associated with the connection then this
4778** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004779*/
danda9fe0c2010-07-13 18:44:03 +00004780static int unixShmUnmap(
4781 sqlite3_file *fd, /* The underlying database file */
4782 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004783){
danda9fe0c2010-07-13 18:44:03 +00004784 unixShm *p; /* The connection to be closed */
4785 unixShmNode *pShmNode; /* The underlying shared-memory file */
4786 unixShm **pp; /* For looping over sibling connections */
4787 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004788
danda9fe0c2010-07-13 18:44:03 +00004789 pDbFd = (unixFile*)fd;
4790 p = pDbFd->pShm;
4791 if( p==0 ) return SQLITE_OK;
4792 pShmNode = p->pShmNode;
4793
4794 assert( pShmNode==pDbFd->pInode->pShmNode );
4795 assert( pShmNode->pInode==pDbFd->pInode );
4796
4797 /* Remove connection p from the set of connections associated
4798 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004799 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004800 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4801 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004802
danda9fe0c2010-07-13 18:44:03 +00004803 /* Free the connection p */
4804 sqlite3_free(p);
4805 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004806 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004807
4808 /* If pShmNode->nRef has reached 0, then close the underlying
4809 ** shared-memory file, too */
4810 unixEnterMutex();
4811 assert( pShmNode->nRef>0 );
4812 pShmNode->nRef--;
4813 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004814 if( deleteFlag && pShmNode->h>=0 ){
4815 osUnlink(pShmNode->zFilename);
4816 }
danda9fe0c2010-07-13 18:44:03 +00004817 unixShmPurge(pDbFd);
4818 }
4819 unixLeaveMutex();
4820
4821 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004822}
drh286a2882010-05-20 23:51:06 +00004823
danda9fe0c2010-07-13 18:44:03 +00004824
drhd9e5c4f2010-05-12 18:01:39 +00004825#else
drh6b017cc2010-06-14 18:01:46 +00004826# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004827# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004828# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004829# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004830#endif /* #ifndef SQLITE_OMIT_WAL */
4831
mistachkine98844f2013-08-24 00:59:24 +00004832#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004833/*
danaef49d72013-03-25 16:28:54 +00004834** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004835*/
danf23da962013-03-23 21:00:41 +00004836static void unixUnmapfile(unixFile *pFd){
4837 assert( pFd->nFetchOut==0 );
4838 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004839 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004840 pFd->pMapRegion = 0;
4841 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004842 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004843 }
4844}
dan5d8a1372013-03-19 19:28:06 +00004845
danaef49d72013-03-25 16:28:54 +00004846/*
dane6ecd662013-04-01 17:56:59 +00004847** Attempt to set the size of the memory mapping maintained by file
4848** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4849**
4850** If successful, this function sets the following variables:
4851**
4852** unixFile.pMapRegion
4853** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004854** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004855**
4856** If unsuccessful, an error message is logged via sqlite3_log() and
4857** the three variables above are zeroed. In this case SQLite should
4858** continue accessing the database using the xRead() and xWrite()
4859** methods.
4860*/
4861static void unixRemapfile(
4862 unixFile *pFd, /* File descriptor object */
4863 i64 nNew /* Required mapping size */
4864){
dan4ff7bc42013-04-02 12:04:09 +00004865 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004866 int h = pFd->h; /* File descriptor open on db file */
4867 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004868 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004869 u8 *pNew = 0; /* Location of new mapping */
4870 int flags = PROT_READ; /* Flags to pass to mmap() */
4871
4872 assert( pFd->nFetchOut==0 );
4873 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004874 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004875 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004876 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004877 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004878
danfe33e392015-11-17 20:56:06 +00004879#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004880 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004881#endif
dane6ecd662013-04-01 17:56:59 +00004882
4883 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004884#if HAVE_MREMAP
4885 i64 nReuse = pFd->mmapSize;
4886#else
danbc760632014-03-20 09:42:09 +00004887 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004888 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004889#endif
dane6ecd662013-04-01 17:56:59 +00004890 u8 *pReq = &pOrig[nReuse];
4891
4892 /* Unmap any pages of the existing mapping that cannot be reused. */
4893 if( nReuse!=nOrig ){
4894 osMunmap(pReq, nOrig-nReuse);
4895 }
4896
4897#if HAVE_MREMAP
4898 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004899 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004900#else
4901 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4902 if( pNew!=MAP_FAILED ){
4903 if( pNew!=pReq ){
4904 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004905 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004906 }else{
4907 pNew = pOrig;
4908 }
4909 }
4910#endif
4911
dan48ccef82013-04-02 20:55:01 +00004912 /* The attempt to extend the existing mapping failed. Free it. */
4913 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004914 osMunmap(pOrig, nReuse);
4915 }
4916 }
4917
4918 /* If pNew is still NULL, try to create an entirely new mapping. */
4919 if( pNew==0 ){
4920 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004921 }
4922
dan4ff7bc42013-04-02 12:04:09 +00004923 if( pNew==MAP_FAILED ){
4924 pNew = 0;
4925 nNew = 0;
4926 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4927
4928 /* If the mmap() above failed, assume that all subsequent mmap() calls
4929 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4930 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004931 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004932 }
dane6ecd662013-04-01 17:56:59 +00004933 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004934 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004935}
4936
4937/*
danaef49d72013-03-25 16:28:54 +00004938** Memory map or remap the file opened by file-descriptor pFd (if the file
4939** is already mapped, the existing mapping is replaced by the new). Or, if
4940** there already exists a mapping for this file, and there are still
4941** outstanding xFetch() references to it, this function is a no-op.
4942**
4943** If parameter nByte is non-negative, then it is the requested size of
4944** the mapping to create. Otherwise, if nByte is less than zero, then the
4945** requested size is the size of the file on disk. The actual size of the
4946** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004947** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004948**
4949** SQLITE_OK is returned if no error occurs (even if the mapping is not
4950** recreated as a result of outstanding references) or an SQLite error
4951** code otherwise.
4952*/
drhf3b1ed02015-12-02 13:11:03 +00004953static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004954 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004955 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004956 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4957
4958 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004959 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004960 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004961 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004962 }
drh3044b512014-06-16 16:41:52 +00004963 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004964 }
drh9b4c59f2013-04-15 17:03:42 +00004965 if( nMap>pFd->mmapSizeMax ){
4966 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004967 }
4968
drh333e6ca2015-12-02 15:44:39 +00004969 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004970 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004971 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004972 }
4973
danf23da962013-03-23 21:00:41 +00004974 return SQLITE_OK;
4975}
mistachkine98844f2013-08-24 00:59:24 +00004976#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004977
danaef49d72013-03-25 16:28:54 +00004978/*
4979** If possible, return a pointer to a mapping of file fd starting at offset
4980** iOff. The mapping must be valid for at least nAmt bytes.
4981**
4982** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4983** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4984** Finally, if an error does occur, return an SQLite error code. The final
4985** value of *pp is undefined in this case.
4986**
4987** If this function does return a pointer, the caller must eventually
4988** release the reference by calling unixUnfetch().
4989*/
danf23da962013-03-23 21:00:41 +00004990static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004991#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004992 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004993#endif
danf23da962013-03-23 21:00:41 +00004994 *pp = 0;
4995
drh9b4c59f2013-04-15 17:03:42 +00004996#if SQLITE_MAX_MMAP_SIZE>0
4997 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004998 if( pFd->pMapRegion==0 ){
4999 int rc = unixMapfile(pFd, -1);
5000 if( rc!=SQLITE_OK ) return rc;
5001 }
5002 if( pFd->mmapSize >= iOff+nAmt ){
5003 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5004 pFd->nFetchOut++;
5005 }
5006 }
drh6e0b6d52013-04-09 16:19:20 +00005007#endif
danf23da962013-03-23 21:00:41 +00005008 return SQLITE_OK;
5009}
5010
danaef49d72013-03-25 16:28:54 +00005011/*
dandf737fe2013-03-25 17:00:24 +00005012** If the third argument is non-NULL, then this function releases a
5013** reference obtained by an earlier call to unixFetch(). The second
5014** argument passed to this function must be the same as the corresponding
5015** argument that was passed to the unixFetch() invocation.
5016**
5017** Or, if the third argument is NULL, then this function is being called
5018** to inform the VFS layer that, according to POSIX, any existing mapping
5019** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005020*/
dandf737fe2013-03-25 17:00:24 +00005021static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005022#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005023 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005024 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005025
danaef49d72013-03-25 16:28:54 +00005026 /* If p==0 (unmap the entire file) then there must be no outstanding
5027 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5028 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005029 assert( (p==0)==(pFd->nFetchOut==0) );
5030
dandf737fe2013-03-25 17:00:24 +00005031 /* If p!=0, it must match the iOff value. */
5032 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5033
danf23da962013-03-23 21:00:41 +00005034 if( p ){
5035 pFd->nFetchOut--;
5036 }else{
5037 unixUnmapfile(pFd);
5038 }
5039
5040 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005041#else
5042 UNUSED_PARAMETER(fd);
5043 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005044 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005045#endif
danf23da962013-03-23 21:00:41 +00005046 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005047}
5048
5049/*
drh734c9862008-11-28 15:37:20 +00005050** Here ends the implementation of all sqlite3_file methods.
5051**
5052********************** End sqlite3_file Methods *******************************
5053******************************************************************************/
5054
5055/*
drh6b9d6dd2008-12-03 19:34:47 +00005056** This division contains definitions of sqlite3_io_methods objects that
5057** implement various file locking strategies. It also contains definitions
5058** of "finder" functions. A finder-function is used to locate the appropriate
5059** sqlite3_io_methods object for a particular database file. The pAppData
5060** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5061** the correct finder-function for that VFS.
5062**
5063** Most finder functions return a pointer to a fixed sqlite3_io_methods
5064** object. The only interesting finder-function is autolockIoFinder, which
5065** looks at the filesystem type and tries to guess the best locking
5066** strategy from that.
5067**
peter.d.reid60ec9142014-09-06 16:39:46 +00005068** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005069**
5070** (1) The real finder-function named "FImpt()".
5071**
dane946c392009-08-22 11:39:46 +00005072** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005073**
5074**
5075** A pointer to the F pointer is used as the pAppData value for VFS
5076** objects. We have to do this instead of letting pAppData point
5077** directly at the finder-function since C90 rules prevent a void*
5078** from be cast into a function pointer.
5079**
drh6b9d6dd2008-12-03 19:34:47 +00005080**
drh7708e972008-11-29 00:56:52 +00005081** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005082**
drh7708e972008-11-29 00:56:52 +00005083** * A constant sqlite3_io_methods object call METHOD that has locking
5084** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5085**
5086** * An I/O method finder function called FINDER that returns a pointer
5087** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005088*/
drhe6d41732015-02-21 00:49:00 +00005089#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005090static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005091 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005092 CLOSE, /* xClose */ \
5093 unixRead, /* xRead */ \
5094 unixWrite, /* xWrite */ \
5095 unixTruncate, /* xTruncate */ \
5096 unixSync, /* xSync */ \
5097 unixFileSize, /* xFileSize */ \
5098 LOCK, /* xLock */ \
5099 UNLOCK, /* xUnlock */ \
5100 CKLOCK, /* xCheckReservedLock */ \
5101 unixFileControl, /* xFileControl */ \
5102 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005103 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005104 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005105 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005106 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005107 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005108 unixFetch, /* xFetch */ \
5109 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005110}; \
drh0c2694b2009-09-03 16:23:44 +00005111static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5112 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005113 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005114} \
drh0c2694b2009-09-03 16:23:44 +00005115static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005116 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005117
5118/*
5119** Here are all of the sqlite3_io_methods objects for each of the
5120** locking strategies. Functions that return pointers to these methods
5121** are also created.
5122*/
5123IOMETHODS(
5124 posixIoFinder, /* Finder function name */
5125 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005126 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005127 unixClose, /* xClose method */
5128 unixLock, /* xLock method */
5129 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005130 unixCheckReservedLock, /* xCheckReservedLock method */
5131 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005132)
drh7708e972008-11-29 00:56:52 +00005133IOMETHODS(
5134 nolockIoFinder, /* Finder function name */
5135 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005136 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005137 nolockClose, /* xClose method */
5138 nolockLock, /* xLock method */
5139 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005140 nolockCheckReservedLock, /* xCheckReservedLock method */
5141 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005142)
drh7708e972008-11-29 00:56:52 +00005143IOMETHODS(
5144 dotlockIoFinder, /* Finder function name */
5145 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005146 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005147 dotlockClose, /* xClose method */
5148 dotlockLock, /* xLock method */
5149 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005150 dotlockCheckReservedLock, /* xCheckReservedLock method */
5151 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005152)
drh7708e972008-11-29 00:56:52 +00005153
drhe89b2912015-03-03 20:42:01 +00005154#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005155IOMETHODS(
5156 flockIoFinder, /* Finder function name */
5157 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005158 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005159 flockClose, /* xClose method */
5160 flockLock, /* xLock method */
5161 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005162 flockCheckReservedLock, /* xCheckReservedLock method */
5163 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005164)
drh7708e972008-11-29 00:56:52 +00005165#endif
5166
drh6c7d5c52008-11-21 20:32:33 +00005167#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005168IOMETHODS(
5169 semIoFinder, /* Finder function name */
5170 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005171 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005172 semXClose, /* xClose method */
5173 semXLock, /* xLock method */
5174 semXUnlock, /* xUnlock method */
5175 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005176 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005177)
aswiftaebf4132008-11-21 00:10:35 +00005178#endif
drh7708e972008-11-29 00:56:52 +00005179
drhd2cb50b2009-01-09 21:41:17 +00005180#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005181IOMETHODS(
5182 afpIoFinder, /* Finder function name */
5183 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005184 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005185 afpClose, /* xClose method */
5186 afpLock, /* xLock method */
5187 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005188 afpCheckReservedLock, /* xCheckReservedLock method */
5189 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005190)
drh715ff302008-12-03 22:32:44 +00005191#endif
5192
5193/*
5194** The proxy locking method is a "super-method" in the sense that it
5195** opens secondary file descriptors for the conch and lock files and
5196** it uses proxy, dot-file, AFP, and flock() locking methods on those
5197** secondary files. For this reason, the division that implements
5198** proxy locking is located much further down in the file. But we need
5199** to go ahead and define the sqlite3_io_methods and finder function
5200** for proxy locking here. So we forward declare the I/O methods.
5201*/
drhd2cb50b2009-01-09 21:41:17 +00005202#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005203static int proxyClose(sqlite3_file*);
5204static int proxyLock(sqlite3_file*, int);
5205static int proxyUnlock(sqlite3_file*, int);
5206static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005207IOMETHODS(
5208 proxyIoFinder, /* Finder function name */
5209 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005210 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005211 proxyClose, /* xClose method */
5212 proxyLock, /* xLock method */
5213 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005214 proxyCheckReservedLock, /* xCheckReservedLock method */
5215 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005216)
aswiftaebf4132008-11-21 00:10:35 +00005217#endif
drh7708e972008-11-29 00:56:52 +00005218
drh7ed97b92010-01-20 13:07:21 +00005219/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5220#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5221IOMETHODS(
5222 nfsIoFinder, /* Finder function name */
5223 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005224 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005225 unixClose, /* xClose method */
5226 unixLock, /* xLock method */
5227 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005228 unixCheckReservedLock, /* xCheckReservedLock method */
5229 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005230)
5231#endif
drh7708e972008-11-29 00:56:52 +00005232
drhd2cb50b2009-01-09 21:41:17 +00005233#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005234/*
drh6b9d6dd2008-12-03 19:34:47 +00005235** This "finder" function attempts to determine the best locking strategy
5236** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005237** object that implements that strategy.
5238**
5239** This is for MacOSX only.
5240*/
drh1875f7a2008-12-08 18:19:17 +00005241static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005242 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005243 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005244){
5245 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005246 const char *zFilesystem; /* Filesystem type name */
5247 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005248 } aMap[] = {
5249 { "hfs", &posixIoMethods },
5250 { "ufs", &posixIoMethods },
5251 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005252 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005253 { "webdav", &nolockIoMethods },
5254 { 0, 0 }
5255 };
5256 int i;
5257 struct statfs fsInfo;
5258 struct flock lockInfo;
5259
5260 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005261 /* If filePath==NULL that means we are dealing with a transient file
5262 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005263 return &nolockIoMethods;
5264 }
5265 if( statfs(filePath, &fsInfo) != -1 ){
5266 if( fsInfo.f_flags & MNT_RDONLY ){
5267 return &nolockIoMethods;
5268 }
5269 for(i=0; aMap[i].zFilesystem; i++){
5270 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5271 return aMap[i].pMethods;
5272 }
5273 }
5274 }
5275
5276 /* Default case. Handles, amongst others, "nfs".
5277 ** Test byte-range lock using fcntl(). If the call succeeds,
5278 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005279 */
drh7708e972008-11-29 00:56:52 +00005280 lockInfo.l_len = 1;
5281 lockInfo.l_start = 0;
5282 lockInfo.l_whence = SEEK_SET;
5283 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005284 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005285 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5286 return &nfsIoMethods;
5287 } else {
5288 return &posixIoMethods;
5289 }
drh7708e972008-11-29 00:56:52 +00005290 }else{
5291 return &dotlockIoMethods;
5292 }
5293}
drh0c2694b2009-09-03 16:23:44 +00005294static const sqlite3_io_methods
5295 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005296
drhd2cb50b2009-01-09 21:41:17 +00005297#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005298
drhe89b2912015-03-03 20:42:01 +00005299#if OS_VXWORKS
5300/*
5301** This "finder" function for VxWorks checks to see if posix advisory
5302** locking works. If it does, then that is what is used. If it does not
5303** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005304*/
drhe89b2912015-03-03 20:42:01 +00005305static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005306 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005307 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005308){
5309 struct flock lockInfo;
5310
5311 if( !filePath ){
5312 /* If filePath==NULL that means we are dealing with a transient file
5313 ** that does not need to be locked. */
5314 return &nolockIoMethods;
5315 }
5316
5317 /* Test if fcntl() is supported and use POSIX style locks.
5318 ** Otherwise fall back to the named semaphore method.
5319 */
5320 lockInfo.l_len = 1;
5321 lockInfo.l_start = 0;
5322 lockInfo.l_whence = SEEK_SET;
5323 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005324 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005325 return &posixIoMethods;
5326 }else{
5327 return &semIoMethods;
5328 }
5329}
drh0c2694b2009-09-03 16:23:44 +00005330static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005331 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005332
drhe89b2912015-03-03 20:42:01 +00005333#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005334
drh7708e972008-11-29 00:56:52 +00005335/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005336** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005337*/
drh0c2694b2009-09-03 16:23:44 +00005338typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005339
aswiftaebf4132008-11-21 00:10:35 +00005340
drh734c9862008-11-28 15:37:20 +00005341/****************************************************************************
5342**************************** sqlite3_vfs methods ****************************
5343**
5344** This division contains the implementation of methods on the
5345** sqlite3_vfs object.
5346*/
5347
danielk1977a3d4c882007-03-23 10:08:38 +00005348/*
danielk1977e339d652008-06-28 11:23:00 +00005349** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005350*/
5351static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005352 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005353 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005354 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005355 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005356 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005357){
drh7708e972008-11-29 00:56:52 +00005358 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005359 unixFile *pNew = (unixFile *)pId;
5360 int rc = SQLITE_OK;
5361
drh8af6c222010-05-14 12:43:01 +00005362 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005363
drhb07028f2011-10-14 21:49:18 +00005364 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005365 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005366
drh308c2a52010-05-14 11:30:18 +00005367 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005368 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005369 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005370 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005371 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005372#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005373 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005374#endif
drhc02a43a2012-01-10 23:18:38 +00005375 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5376 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005377 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005378 }
drh503a6862013-03-01 01:07:17 +00005379 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005380 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005381 }
drh339eb0b2008-03-07 15:34:11 +00005382
drh6c7d5c52008-11-21 20:32:33 +00005383#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005384 pNew->pId = vxworksFindFileId(zFilename);
5385 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005386 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005387 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005388 }
5389#endif
5390
drhc02a43a2012-01-10 23:18:38 +00005391 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005392 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005393 }else{
drh0c2694b2009-09-03 16:23:44 +00005394 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005395#if SQLITE_ENABLE_LOCKING_STYLE
5396 /* Cache zFilename in the locking context (AFP and dotlock override) for
5397 ** proxyLock activation is possible (remote proxy is based on db name)
5398 ** zFilename remains valid until file is closed, to support */
5399 pNew->lockingContext = (void*)zFilename;
5400#endif
drhda0e7682008-07-30 15:27:54 +00005401 }
danielk1977e339d652008-06-28 11:23:00 +00005402
drh7ed97b92010-01-20 13:07:21 +00005403 if( pLockingStyle == &posixIoMethods
5404#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5405 || pLockingStyle == &nfsIoMethods
5406#endif
5407 ){
drh7708e972008-11-29 00:56:52 +00005408 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005409 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005410 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005411 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005412 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005413 ** in two scenarios:
5414 **
5415 ** (a) A call to fstat() failed.
5416 ** (b) A malloc failed.
5417 **
5418 ** Scenario (b) may only occur if the process is holding no other
5419 ** file descriptors open on the same file. If there were other file
5420 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005421 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005422 ** handle h - as it is guaranteed that no posix locks will be released
5423 ** by doing so.
5424 **
5425 ** If scenario (a) caused the error then things are not so safe. The
5426 ** implicit assumption here is that if fstat() fails, things are in
5427 ** such bad shape that dropping a lock or two doesn't matter much.
5428 */
drh0e9365c2011-03-02 02:08:13 +00005429 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005430 h = -1;
5431 }
drh7708e972008-11-29 00:56:52 +00005432 unixLeaveMutex();
5433 }
danielk1977e339d652008-06-28 11:23:00 +00005434
drhd2cb50b2009-01-09 21:41:17 +00005435#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005436 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005437 /* AFP locking uses the file path so it needs to be included in
5438 ** the afpLockingContext.
5439 */
5440 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005441 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005442 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005443 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005444 }else{
5445 /* NB: zFilename exists and remains valid until the file is closed
5446 ** according to requirement F11141. So we do not need to make a
5447 ** copy of the filename. */
5448 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005449 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005450 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005451 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005452 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005453 if( rc!=SQLITE_OK ){
5454 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005455 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005456 h = -1;
5457 }
drh7708e972008-11-29 00:56:52 +00005458 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005459 }
drh7708e972008-11-29 00:56:52 +00005460 }
5461#endif
danielk1977e339d652008-06-28 11:23:00 +00005462
drh7708e972008-11-29 00:56:52 +00005463 else if( pLockingStyle == &dotlockIoMethods ){
5464 /* Dotfile locking uses the file path so it needs to be included in
5465 ** the dotlockLockingContext
5466 */
5467 char *zLockFile;
5468 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005469 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005470 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005471 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005472 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005473 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005474 }else{
5475 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005476 }
drh7708e972008-11-29 00:56:52 +00005477 pNew->lockingContext = zLockFile;
5478 }
danielk1977e339d652008-06-28 11:23:00 +00005479
drh6c7d5c52008-11-21 20:32:33 +00005480#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005481 else if( pLockingStyle == &semIoMethods ){
5482 /* Named semaphore locking uses the file path so it needs to be
5483 ** included in the semLockingContext
5484 */
5485 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005486 rc = findInodeInfo(pNew, &pNew->pInode);
5487 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5488 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005489 int n;
drh2238dcc2009-08-27 17:56:20 +00005490 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005491 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005492 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005493 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005494 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5495 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005496 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005497 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005498 }
chw97185482008-11-17 08:05:31 +00005499 }
drh7708e972008-11-29 00:56:52 +00005500 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005501 }
drh7708e972008-11-29 00:56:52 +00005502#endif
aswift5b1a2562008-08-22 00:22:35 +00005503
drh4bf66fd2015-02-19 02:43:02 +00005504 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005505#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005506 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005507 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005508 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005509 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005510 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005511 }
chw97185482008-11-17 08:05:31 +00005512#endif
danielk1977e339d652008-06-28 11:23:00 +00005513 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005514 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005515 }else{
drh7708e972008-11-29 00:56:52 +00005516 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005517 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005518 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005519 }
danielk1977e339d652008-06-28 11:23:00 +00005520 return rc;
drh054889e2005-11-30 03:20:31 +00005521}
drh9c06c952005-11-26 00:25:00 +00005522
danielk1977ad94b582007-08-20 06:44:22 +00005523/*
drh8b3cf822010-06-01 21:02:51 +00005524** Return the name of a directory in which to put temporary files.
5525** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005526*/
drh7234c6d2010-06-19 15:10:09 +00005527static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005528 static const char *azDirs[] = {
5529 0,
aswiftaebf4132008-11-21 00:10:35 +00005530 0,
danielk197717b90b52008-06-06 11:11:25 +00005531 "/var/tmp",
5532 "/usr/tmp",
5533 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005534 "."
danielk197717b90b52008-06-06 11:11:25 +00005535 };
drh2aab11f2016-04-29 20:30:56 +00005536 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005537 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005538 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005539
drhb7e50ad2015-11-28 21:49:53 +00005540 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5541 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005542 while(1){
5543 if( zDir!=0
5544 && osStat(zDir, &buf)==0
5545 && S_ISDIR(buf.st_mode)
5546 && osAccess(zDir, 03)==0
5547 ){
5548 return zDir;
5549 }
5550 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5551 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005552 }
drh7694e062016-04-21 23:37:24 +00005553 return 0;
drh8b3cf822010-06-01 21:02:51 +00005554}
5555
5556/*
5557** Create a temporary file name in zBuf. zBuf must be allocated
5558** by the calling process and must be big enough to hold at least
5559** pVfs->mxPathname bytes.
5560*/
5561static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005562 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005563 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005564
5565 /* It's odd to simulate an io-error here, but really this is just
5566 ** using the io-error infrastructure to test that SQLite handles this
5567 ** function failing.
5568 */
drh7694e062016-04-21 23:37:24 +00005569 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005570 SimulateIOError( return SQLITE_IOERR );
5571
drh7234c6d2010-06-19 15:10:09 +00005572 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005573 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005574 do{
drh970942e2015-11-25 23:13:14 +00005575 u64 r;
5576 sqlite3_randomness(sizeof(r), &r);
5577 assert( nBuf>2 );
5578 zBuf[nBuf-2] = 0;
5579 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5580 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005581 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005582 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005583 return SQLITE_OK;
5584}
5585
drhd2cb50b2009-01-09 21:41:17 +00005586#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005587/*
5588** Routine to transform a unixFile into a proxy-locking unixFile.
5589** Implementation in the proxy-lock division, but used by unixOpen()
5590** if SQLITE_PREFER_PROXY_LOCKING is defined.
5591*/
5592static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005593#endif
drhc66d5b62008-12-03 22:48:32 +00005594
dan08da86a2009-08-21 17:18:03 +00005595/*
5596** Search for an unused file descriptor that was opened on the database
5597** file (not a journal or master-journal file) identified by pathname
5598** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5599** argument to this function.
5600**
5601** Such a file descriptor may exist if a database connection was closed
5602** but the associated file descriptor could not be closed because some
5603** other file descriptor open on the same file is holding a file-lock.
5604** Refer to comments in the unixClose() function and the lengthy comment
5605** describing "Posix Advisory Locking" at the start of this file for
5606** further details. Also, ticket #4018.
5607**
5608** If a suitable file descriptor is found, then it is returned. If no
5609** such file descriptor is located, -1 is returned.
5610*/
dane946c392009-08-22 11:39:46 +00005611static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5612 UnixUnusedFd *pUnused = 0;
5613
5614 /* Do not search for an unused file descriptor on vxworks. Not because
5615 ** vxworks would not benefit from the change (it might, we're not sure),
5616 ** but because no way to test it is currently available. It is better
5617 ** not to risk breaking vxworks support for the sake of such an obscure
5618 ** feature. */
5619#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005620 struct stat sStat; /* Results of stat() call */
5621
drhc68886b2017-08-18 16:09:52 +00005622 unixEnterMutex();
5623
dan08da86a2009-08-21 17:18:03 +00005624 /* A stat() call may fail for various reasons. If this happens, it is
5625 ** almost certain that an open() call on the same path will also fail.
5626 ** For this reason, if an error occurs in the stat() call here, it is
5627 ** ignored and -1 is returned. The caller will try to open a new file
5628 ** descriptor on the same path, fail, and return an error to SQLite.
5629 **
5630 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005631 ** not searching for a reusable file descriptor are not dire. */
drhc68886b2017-08-18 16:09:52 +00005632 if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005633 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005634
drh8af6c222010-05-14 12:43:01 +00005635 pInode = inodeList;
5636 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005637 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005638 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005639 }
drh8af6c222010-05-14 12:43:01 +00005640 if( pInode ){
dane946c392009-08-22 11:39:46 +00005641 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005642 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005643 pUnused = *pp;
5644 if( pUnused ){
drhc68886b2017-08-18 16:09:52 +00005645 nUnusedFd--;
dane946c392009-08-22 11:39:46 +00005646 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005647 }
5648 }
dan08da86a2009-08-21 17:18:03 +00005649 }
drhc68886b2017-08-18 16:09:52 +00005650 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005651#endif /* if !OS_VXWORKS */
5652 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005653}
danielk197717b90b52008-06-06 11:11:25 +00005654
5655/*
dan1bf4ca72016-08-11 18:05:47 +00005656** Find the mode, uid and gid of file zFile.
5657*/
5658static int getFileMode(
5659 const char *zFile, /* File name */
5660 mode_t *pMode, /* OUT: Permissions of zFile */
5661 uid_t *pUid, /* OUT: uid of zFile. */
5662 gid_t *pGid /* OUT: gid of zFile. */
5663){
5664 struct stat sStat; /* Output of stat() on database file */
5665 int rc = SQLITE_OK;
5666 if( 0==osStat(zFile, &sStat) ){
5667 *pMode = sStat.st_mode & 0777;
5668 *pUid = sStat.st_uid;
5669 *pGid = sStat.st_gid;
5670 }else{
5671 rc = SQLITE_IOERR_FSTAT;
5672 }
5673 return rc;
5674}
5675
5676/*
danddb0ac42010-07-14 14:48:58 +00005677** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005678** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005679** and a value suitable for passing as the third argument to open(2) is
5680** written to *pMode. If an IO error occurs, an SQLite error code is
5681** returned and the value of *pMode is not modified.
5682**
peter.d.reid60ec9142014-09-06 16:39:46 +00005683** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005684** an indication to robust_open() to create the file using
5685** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5686** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005687** this function queries the file-system for the permissions on the
5688** corresponding database file and sets *pMode to this value. Whenever
5689** possible, WAL and journal files are created using the same permissions
5690** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005691**
5692** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5693** original filename is unavailable. But 8_3_NAMES is only used for
5694** FAT filesystems and permissions do not matter there, so just use
5695** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005696*/
5697static int findCreateFileMode(
5698 const char *zPath, /* Path of file (possibly) being created */
5699 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005700 mode_t *pMode, /* OUT: Permissions to open file with */
5701 uid_t *pUid, /* OUT: uid to set on the file */
5702 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005703){
5704 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005705 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005706 *pUid = 0;
5707 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005708 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005709 char zDb[MAX_PATHNAME+1]; /* Database file path */
5710 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005711
dana0c989d2010-11-05 18:07:37 +00005712 /* zPath is a path to a WAL or journal file. The following block derives
5713 ** the path to the associated database file from zPath. This block handles
5714 ** the following naming conventions:
5715 **
5716 ** "<path to db>-journal"
5717 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005718 ** "<path to db>-journalNN"
5719 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005720 **
drhd337c5b2011-10-20 18:23:35 +00005721 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005722 ** used by the test_multiplex.c module.
5723 */
5724 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005725 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005726 /* In normal operation, the journal file name will always contain
5727 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5728 ** rollback journal specifies a master journal with a goofy name, then
5729 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005730 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005731 nDb--;
5732 }
danddb0ac42010-07-14 14:48:58 +00005733 memcpy(zDb, zPath, nDb);
5734 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005735
dan1bf4ca72016-08-11 18:05:47 +00005736 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005737 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5738 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005739 }else if( flags & SQLITE_OPEN_URI ){
5740 /* If this is a main database file and the file was opened using a URI
5741 ** filename, check for the "modeof" parameter. If present, interpret
5742 ** its value as a filename and try to copy the mode, uid and gid from
5743 ** that file. */
5744 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5745 if( z ){
5746 rc = getFileMode(z, pMode, pUid, pGid);
5747 }
danddb0ac42010-07-14 14:48:58 +00005748 }
5749 return rc;
5750}
5751
5752/*
danielk1977ad94b582007-08-20 06:44:22 +00005753** Open the file zPath.
5754**
danielk1977b4b47412007-08-17 15:53:36 +00005755** Previously, the SQLite OS layer used three functions in place of this
5756** one:
5757**
5758** sqlite3OsOpenReadWrite();
5759** sqlite3OsOpenReadOnly();
5760** sqlite3OsOpenExclusive();
5761**
5762** These calls correspond to the following combinations of flags:
5763**
5764** ReadWrite() -> (READWRITE | CREATE)
5765** ReadOnly() -> (READONLY)
5766** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5767**
5768** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5769** true, the file was configured to be automatically deleted when the
5770** file handle closed. To achieve the same effect using this new
5771** interface, add the DELETEONCLOSE flag to those specified above for
5772** OpenExclusive().
5773*/
5774static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005775 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5776 const char *zPath, /* Pathname of file to be opened */
5777 sqlite3_file *pFile, /* The file descriptor to be filled in */
5778 int flags, /* Input flags to control the opening */
5779 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005780){
dan08da86a2009-08-21 17:18:03 +00005781 unixFile *p = (unixFile *)pFile;
5782 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005783 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005784 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005785 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005786 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005787 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005788
5789 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5790 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5791 int isCreate = (flags & SQLITE_OPEN_CREATE);
5792 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5793 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005794#if SQLITE_ENABLE_LOCKING_STYLE
5795 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5796#endif
drh3d4435b2011-08-26 20:55:50 +00005797#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5798 struct statfs fsInfo;
5799#endif
danielk1977b4b47412007-08-17 15:53:36 +00005800
danielk1977fee2d252007-08-18 10:59:19 +00005801 /* If creating a master or main-file journal, this function will open
5802 ** a file-descriptor on the directory too. The first time unixSync()
5803 ** is called the directory file descriptor will be fsync()ed and close()d.
5804 */
drha803a2c2017-12-13 20:02:29 +00005805 int isNewJrnl = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005806 eType==SQLITE_OPEN_MASTER_JOURNAL
5807 || eType==SQLITE_OPEN_MAIN_JOURNAL
5808 || eType==SQLITE_OPEN_WAL
5809 ));
danielk1977fee2d252007-08-18 10:59:19 +00005810
danielk197717b90b52008-06-06 11:11:25 +00005811 /* If argument zPath is a NULL pointer, this function is required to open
5812 ** a temporary file. Use this buffer to store the file name in.
5813 */
drhc02a43a2012-01-10 23:18:38 +00005814 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005815 const char *zName = zPath;
5816
danielk1977fee2d252007-08-18 10:59:19 +00005817 /* Check the following statements are true:
5818 **
5819 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5820 ** (b) if CREATE is set, then READWRITE must also be set, and
5821 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005822 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005823 */
danielk1977b4b47412007-08-17 15:53:36 +00005824 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005825 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005826 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005827 assert(isDelete==0 || isCreate);
5828
danddb0ac42010-07-14 14:48:58 +00005829 /* The main DB, main journal, WAL file and master journal are never
5830 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005831 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5832 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5833 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005834 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005835
danielk1977fee2d252007-08-18 10:59:19 +00005836 /* Assert that the upper layer has set one of the "file-type" flags. */
5837 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5838 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5839 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005840 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005841 );
5842
drhb00d8622014-01-01 15:18:36 +00005843 /* Detect a pid change and reset the PRNG. There is a race condition
5844 ** here such that two or more threads all trying to open databases at
5845 ** the same instant might all reset the PRNG. But multiple resets
5846 ** are harmless.
5847 */
drh5ac93652015-03-21 20:59:43 +00005848 if( randomnessPid!=osGetpid(0) ){
5849 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005850 sqlite3_randomness(0,0);
5851 }
dan08da86a2009-08-21 17:18:03 +00005852 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005853
dan08da86a2009-08-21 17:18:03 +00005854 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005855 UnixUnusedFd *pUnused;
5856 pUnused = findReusableFd(zName, flags);
5857 if( pUnused ){
5858 fd = pUnused->fd;
5859 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005860 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005861 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005862 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005863 }
5864 }
drhc68886b2017-08-18 16:09:52 +00005865 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005866
5867 /* Database filenames are double-zero terminated if they are not
5868 ** URIs with parameters. Hence, they can always be passed into
5869 ** sqlite3_uri_parameter(). */
5870 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5871
dan08da86a2009-08-21 17:18:03 +00005872 }else if( !zName ){
5873 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00005874 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00005875 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005876 if( rc!=SQLITE_OK ){
5877 return rc;
5878 }
5879 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005880
5881 /* Generated temporary filenames are always double-zero terminated
5882 ** for use by sqlite3_uri_parameter(). */
5883 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005884 }
5885
dan08da86a2009-08-21 17:18:03 +00005886 /* Determine the value of the flags parameter passed to POSIX function
5887 ** open(). These must be calculated even if open() is not called, as
5888 ** they may be stored as part of the file handle and used by the
5889 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005890 if( isReadonly ) openFlags |= O_RDONLY;
5891 if( isReadWrite ) openFlags |= O_RDWR;
5892 if( isCreate ) openFlags |= O_CREAT;
5893 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5894 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005895
danielk1977b4b47412007-08-17 15:53:36 +00005896 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005897 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005898 uid_t uid; /* Userid for the file */
5899 gid_t gid; /* Groupid for the file */
5900 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005901 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00005902 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00005903 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005904 return rc;
5905 }
drhad4f1e52011-03-04 15:43:57 +00005906 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005907 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005908 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00005909 if( fd<0 ){
5910 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
5911 /* If unable to create a journal because the directory is not
5912 ** writable, change the error code to indicate that. */
5913 rc = SQLITE_READONLY_DIRECTORY;
5914 }else if( errno!=EISDIR && isReadWrite ){
5915 /* Failed to open the file for read/write access. Try read-only. */
5916 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
5917 openFlags &= ~(O_RDWR|O_CREAT);
5918 flags |= SQLITE_OPEN_READONLY;
5919 openFlags |= O_RDONLY;
5920 isReadonly = 1;
5921 fd = robust_open(zName, openFlags, openMode);
5922 }
dan08da86a2009-08-21 17:18:03 +00005923 }
5924 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00005925 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
5926 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00005927 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005928 }
drhac7c3ac2012-02-11 19:23:48 +00005929
5930 /* If this process is running as root and if creating a new rollback
5931 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005932 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005933 */
5934 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005935 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005936 }
danielk1977b4b47412007-08-17 15:53:36 +00005937 }
dan08da86a2009-08-21 17:18:03 +00005938 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005939 if( pOutFlags ){
5940 *pOutFlags = flags;
5941 }
5942
drhc68886b2017-08-18 16:09:52 +00005943 if( p->pPreallocatedUnused ){
5944 p->pPreallocatedUnused->fd = fd;
5945 p->pPreallocatedUnused->flags = flags;
dane946c392009-08-22 11:39:46 +00005946 }
5947
danielk1977b4b47412007-08-17 15:53:36 +00005948 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005949#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005950 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005951#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5952 zPath = sqlite3_mprintf("%s", zName);
5953 if( zPath==0 ){
5954 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00005955 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00005956 }
chw97185482008-11-17 08:05:31 +00005957#else
drh036ac7f2011-08-08 23:18:05 +00005958 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005959#endif
danielk1977b4b47412007-08-17 15:53:36 +00005960 }
drh41022642008-11-21 00:24:42 +00005961#if SQLITE_ENABLE_LOCKING_STYLE
5962 else{
dan08da86a2009-08-21 17:18:03 +00005963 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005964 }
5965#endif
drh7ed97b92010-01-20 13:07:21 +00005966
5967#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005968 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005969 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005970 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005971 return SQLITE_IOERR_ACCESS;
5972 }
5973 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5974 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5975 }
drh4bf66fd2015-02-19 02:43:02 +00005976 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5977 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5978 }
drh7ed97b92010-01-20 13:07:21 +00005979#endif
drhc02a43a2012-01-10 23:18:38 +00005980
5981 /* Set up appropriate ctrlFlags */
5982 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5983 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00005984 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00005985 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00005986 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00005987 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5988
drh7ed97b92010-01-20 13:07:21 +00005989#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005990#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005991 isAutoProxy = 1;
5992#endif
5993 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005994 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5995 int useProxy = 0;
5996
dan08da86a2009-08-21 17:18:03 +00005997 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5998 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005999 if( envforce!=NULL ){
6000 useProxy = atoi(envforce)>0;
6001 }else{
aswiftaebf4132008-11-21 00:10:35 +00006002 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6003 }
6004 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006005 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006006 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006007 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006008 if( rc!=SQLITE_OK ){
6009 /* Use unixClose to clean up the resources added in fillInUnixFile
6010 ** and clear all the structure's references. Specifically,
6011 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6012 */
6013 unixClose(pFile);
6014 return rc;
6015 }
aswiftaebf4132008-11-21 00:10:35 +00006016 }
dane946c392009-08-22 11:39:46 +00006017 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006018 }
6019 }
6020#endif
6021
dan3ed0f1c2017-09-14 21:12:07 +00006022 assert( zPath==0 || zPath[0]=='/'
6023 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6024 );
drhc02a43a2012-01-10 23:18:38 +00006025 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6026
dane946c392009-08-22 11:39:46 +00006027open_finished:
6028 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006029 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006030 }
6031 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006032}
6033
dane946c392009-08-22 11:39:46 +00006034
danielk1977b4b47412007-08-17 15:53:36 +00006035/*
danielk1977fee2d252007-08-18 10:59:19 +00006036** Delete the file at zPath. If the dirSync argument is true, fsync()
6037** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006038*/
drh6b9d6dd2008-12-03 19:34:47 +00006039static int unixDelete(
6040 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6041 const char *zPath, /* Name of file to be deleted */
6042 int dirSync /* If true, fsync() directory after deleting file */
6043){
danielk1977fee2d252007-08-18 10:59:19 +00006044 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006045 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006046 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006047 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006048 if( errno==ENOENT
6049#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006050 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006051#endif
6052 ){
dan9fc5b4a2012-11-09 20:17:26 +00006053 rc = SQLITE_IOERR_DELETE_NOENT;
6054 }else{
drhb4308162012-11-09 21:40:02 +00006055 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006056 }
drhb4308162012-11-09 21:40:02 +00006057 return rc;
drh5d4feff2010-07-14 01:45:22 +00006058 }
danielk1977d39fa702008-10-16 13:27:40 +00006059#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006060 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006061 int fd;
drh90315a22011-08-10 01:52:12 +00006062 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006063 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006064 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006065 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006066 }
drh0e9365c2011-03-02 02:08:13 +00006067 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006068 }else{
6069 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006070 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006071 }
6072 }
danielk1977d138dd82008-10-15 16:02:48 +00006073#endif
danielk1977fee2d252007-08-18 10:59:19 +00006074 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006075}
6076
danielk197790949c22007-08-17 16:50:38 +00006077/*
mistachkin48864df2013-03-21 21:20:32 +00006078** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006079** test performed depends on the value of flags:
6080**
6081** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6082** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6083** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6084**
6085** Otherwise return 0.
6086*/
danielk1977861f7452008-06-05 11:39:11 +00006087static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006088 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6089 const char *zPath, /* Path of the file to examine */
6090 int flags, /* What do we want to learn about the zPath file? */
6091 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006092){
danielk1977397d65f2008-11-19 11:35:39 +00006093 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006094 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006095 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006096
drhd260b5b2015-11-25 18:03:33 +00006097 /* The spec says there are three possible values for flags. But only
6098 ** two of them are actually used */
6099 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6100
6101 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006102 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006103 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6104 }else{
6105 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006106 }
danielk1977861f7452008-06-05 11:39:11 +00006107 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006108}
6109
danielk1977b4b47412007-08-17 15:53:36 +00006110/*
danielk1977b4b47412007-08-17 15:53:36 +00006111**
danielk1977b4b47412007-08-17 15:53:36 +00006112*/
dane88ec182016-01-25 17:04:48 +00006113static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006114 const char *zPath, /* Input path */
6115 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006116 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006117){
dancaf6b152016-01-25 18:05:49 +00006118 int nPath = sqlite3Strlen30(zPath);
6119 int iOff = 0;
6120 if( zPath[0]!='/' ){
6121 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006122 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006123 }
dancaf6b152016-01-25 18:05:49 +00006124 iOff = sqlite3Strlen30(zOut);
6125 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006126 }
dan23496702016-01-26 13:56:42 +00006127 if( (iOff+nPath+1)>nOut ){
6128 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6129 ** even if it returns an error. */
6130 zOut[iOff] = '\0';
6131 return SQLITE_CANTOPEN_BKPT;
6132 }
dancaf6b152016-01-25 18:05:49 +00006133 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006134 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006135}
6136
dane88ec182016-01-25 17:04:48 +00006137/*
6138** Turn a relative pathname into a full pathname. The relative path
6139** is stored as a nul-terminated string in the buffer pointed to by
6140** zPath.
6141**
6142** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6143** (in this case, MAX_PATHNAME bytes). The full-path is written to
6144** this buffer before returning.
6145*/
6146static int unixFullPathname(
6147 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6148 const char *zPath, /* Possibly relative input path */
6149 int nOut, /* Size of output buffer in bytes */
6150 char *zOut /* Output buffer */
6151){
danaf1b36b2016-01-25 18:43:05 +00006152#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006153 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006154#else
6155 int rc = SQLITE_OK;
6156 int nByte;
dancaf6b152016-01-25 18:05:49 +00006157 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006158 const char *zIn = zPath; /* Input path for each iteration of loop */
6159 char *zDel = 0;
6160
6161 assert( pVfs->mxPathname==MAX_PATHNAME );
6162 UNUSED_PARAMETER(pVfs);
6163
6164 /* It's odd to simulate an io-error here, but really this is just
6165 ** using the io-error infrastructure to test that SQLite handles this
6166 ** function failing. This function could fail if, for example, the
6167 ** current working directory has been unlinked.
6168 */
6169 SimulateIOError( return SQLITE_ERROR );
6170
6171 do {
6172
dancaf6b152016-01-25 18:05:49 +00006173 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6174 ** link, or false otherwise. */
6175 int bLink = 0;
6176 struct stat buf;
6177 if( osLstat(zIn, &buf)!=0 ){
6178 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006179 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006180 }
dane88ec182016-01-25 17:04:48 +00006181 }else{
dancaf6b152016-01-25 18:05:49 +00006182 bLink = S_ISLNK(buf.st_mode);
6183 }
6184
6185 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006186 if( zDel==0 ){
6187 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006188 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006189 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6190 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006191 }
dancaf6b152016-01-25 18:05:49 +00006192
6193 if( rc==SQLITE_OK ){
6194 nByte = osReadlink(zIn, zDel, nOut-1);
6195 if( nByte<0 ){
6196 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006197 }else{
6198 if( zDel[0]!='/' ){
6199 int n;
6200 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6201 if( nByte+n+1>nOut ){
6202 rc = SQLITE_CANTOPEN_BKPT;
6203 }else{
6204 memmove(&zDel[n], zDel, nByte+1);
6205 memcpy(zDel, zIn, n);
6206 nByte += n;
6207 }
dancaf6b152016-01-25 18:05:49 +00006208 }
6209 zDel[nByte] = '\0';
6210 }
6211 }
6212
6213 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006214 }
6215
dan23496702016-01-26 13:56:42 +00006216 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6217 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006218 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006219 }
dancaf6b152016-01-25 18:05:49 +00006220 if( bLink==0 ) break;
6221 zIn = zOut;
6222 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006223
6224 sqlite3_free(zDel);
6225 return rc;
danaf1b36b2016-01-25 18:43:05 +00006226#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006227}
6228
drh0ccebe72005-06-07 22:22:50 +00006229
drh761df872006-12-21 01:29:22 +00006230#ifndef SQLITE_OMIT_LOAD_EXTENSION
6231/*
6232** Interfaces for opening a shared library, finding entry points
6233** within the shared library, and closing the shared library.
6234*/
6235#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006236static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6237 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006238 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6239}
danielk197795c8a542007-09-01 06:51:27 +00006240
6241/*
6242** SQLite calls this function immediately after a call to unixDlSym() or
6243** unixDlOpen() fails (returns a null pointer). If a more detailed error
6244** message is available, it is written to zBufOut. If no error message
6245** is available, zBufOut is left unmodified and SQLite uses a default
6246** error message.
6247*/
danielk1977397d65f2008-11-19 11:35:39 +00006248static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006249 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006250 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006251 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006252 zErr = dlerror();
6253 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006254 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006255 }
drh6c7d5c52008-11-21 20:32:33 +00006256 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006257}
drh1875f7a2008-12-08 18:19:17 +00006258static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6259 /*
6260 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6261 ** cast into a pointer to a function. And yet the library dlsym() routine
6262 ** returns a void* which is really a pointer to a function. So how do we
6263 ** use dlsym() with -pedantic-errors?
6264 **
6265 ** Variable x below is defined to be a pointer to a function taking
6266 ** parameters void* and const char* and returning a pointer to a function.
6267 ** We initialize x by assigning it a pointer to the dlsym() function.
6268 ** (That assignment requires a cast.) Then we call the function that
6269 ** x points to.
6270 **
6271 ** This work-around is unlikely to work correctly on any system where
6272 ** you really cannot cast a function pointer into void*. But then, on the
6273 ** other hand, dlsym() will not work on such a system either, so we have
6274 ** not really lost anything.
6275 */
6276 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006277 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006278 x = (void(*(*)(void*,const char*))(void))dlsym;
6279 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006280}
danielk1977397d65f2008-11-19 11:35:39 +00006281static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6282 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006283 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006284}
danielk1977b4b47412007-08-17 15:53:36 +00006285#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6286 #define unixDlOpen 0
6287 #define unixDlError 0
6288 #define unixDlSym 0
6289 #define unixDlClose 0
6290#endif
6291
6292/*
danielk197790949c22007-08-17 16:50:38 +00006293** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006294*/
danielk1977397d65f2008-11-19 11:35:39 +00006295static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6296 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006297 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006298
drhbbd42a62004-05-22 17:41:58 +00006299 /* We have to initialize zBuf to prevent valgrind from reporting
6300 ** errors. The reports issued by valgrind are incorrect - we would
6301 ** prefer that the randomness be increased by making use of the
6302 ** uninitialized space in zBuf - but valgrind errors tend to worry
6303 ** some users. Rather than argue, it seems easier just to initialize
6304 ** the whole array and silence valgrind, even if that means less randomness
6305 ** in the random seed.
6306 **
6307 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006308 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006309 ** tests repeatable.
6310 */
danielk1977b4b47412007-08-17 15:53:36 +00006311 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006312 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006313#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006314 {
drhb00d8622014-01-01 15:18:36 +00006315 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006316 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006317 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006318 time_t t;
6319 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006320 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006321 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6322 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6323 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006324 }else{
drhc18b4042012-02-10 03:10:27 +00006325 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006326 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006327 }
drhbbd42a62004-05-22 17:41:58 +00006328 }
6329#endif
drh72cbd072008-10-14 17:58:38 +00006330 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006331}
6332
danielk1977b4b47412007-08-17 15:53:36 +00006333
drhbbd42a62004-05-22 17:41:58 +00006334/*
6335** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006336** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006337** The return value is the number of microseconds of sleep actually
6338** requested from the underlying operating system, a number which
6339** might be greater than or equal to the argument, but not less
6340** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006341*/
danielk1977397d65f2008-11-19 11:35:39 +00006342static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006343#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006344 struct timespec sp;
6345
6346 sp.tv_sec = microseconds / 1000000;
6347 sp.tv_nsec = (microseconds % 1000000) * 1000;
6348 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006349 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006350 return microseconds;
6351#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006352 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006353 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006354 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006355#else
danielk1977b4b47412007-08-17 15:53:36 +00006356 int seconds = (microseconds+999999)/1000000;
6357 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006358 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006359 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006360#endif
drh88f474a2006-01-02 20:00:12 +00006361}
6362
6363/*
drh6b9d6dd2008-12-03 19:34:47 +00006364** The following variable, if set to a non-zero value, is interpreted as
6365** the number of seconds since 1970 and is used to set the result of
6366** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006367*/
6368#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006369int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006370#endif
6371
6372/*
drhb7e8ea22010-05-03 14:32:30 +00006373** Find the current time (in Universal Coordinated Time). Write into *piNow
6374** the current time and date as a Julian Day number times 86_400_000. In
6375** other words, write into *piNow the number of milliseconds since the Julian
6376** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6377** proleptic Gregorian calendar.
6378**
drh31702252011-10-12 23:13:43 +00006379** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6380** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006381*/
6382static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6383 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006384 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006385#if defined(NO_GETTOD)
6386 time_t t;
6387 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006388 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006389#elif OS_VXWORKS
6390 struct timespec sNow;
6391 clock_gettime(CLOCK_REALTIME, &sNow);
6392 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6393#else
6394 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006395 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6396 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006397#endif
6398
6399#ifdef SQLITE_TEST
6400 if( sqlite3_current_time ){
6401 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6402 }
6403#endif
6404 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006405 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006406}
6407
drhc3dfa5e2016-01-22 19:44:03 +00006408#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006409/*
drhbbd42a62004-05-22 17:41:58 +00006410** Find the current time (in Universal Coordinated Time). Write the
6411** current time and date as a Julian Day number into *prNow and
6412** return 0. Return 1 if the time and date cannot be found.
6413*/
danielk1977397d65f2008-11-19 11:35:39 +00006414static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006415 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006416 int rc;
drhff828942010-06-26 21:34:06 +00006417 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006418 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006419 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006420 return rc;
drhbbd42a62004-05-22 17:41:58 +00006421}
drh5337dac2015-11-25 15:15:03 +00006422#else
6423# define unixCurrentTime 0
6424#endif
danielk1977b4b47412007-08-17 15:53:36 +00006425
drh6b9d6dd2008-12-03 19:34:47 +00006426/*
drh1b9f2142016-03-17 16:01:23 +00006427** The xGetLastError() method is designed to return a better
6428** low-level error message when operating-system problems come up
6429** during SQLite operation. Only the integer return code is currently
6430** used.
drh6b9d6dd2008-12-03 19:34:47 +00006431*/
danielk1977397d65f2008-11-19 11:35:39 +00006432static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6433 UNUSED_PARAMETER(NotUsed);
6434 UNUSED_PARAMETER(NotUsed2);
6435 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006436 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006437}
6438
drhf2424c52010-04-26 00:04:55 +00006439
6440/*
drh734c9862008-11-28 15:37:20 +00006441************************ End of sqlite3_vfs methods ***************************
6442******************************************************************************/
6443
drh715ff302008-12-03 22:32:44 +00006444/******************************************************************************
6445************************** Begin Proxy Locking ********************************
6446**
6447** Proxy locking is a "uber-locking-method" in this sense: It uses the
6448** other locking methods on secondary lock files. Proxy locking is a
6449** meta-layer over top of the primitive locking implemented above. For
6450** this reason, the division that implements of proxy locking is deferred
6451** until late in the file (here) after all of the other I/O methods have
6452** been defined - so that the primitive locking methods are available
6453** as services to help with the implementation of proxy locking.
6454**
6455****
6456**
6457** The default locking schemes in SQLite use byte-range locks on the
6458** database file to coordinate safe, concurrent access by multiple readers
6459** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6460** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6461** as POSIX read & write locks over fixed set of locations (via fsctl),
6462** on AFP and SMB only exclusive byte-range locks are available via fsctl
6463** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6464** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6465** address in the shared range is taken for a SHARED lock, the entire
6466** shared range is taken for an EXCLUSIVE lock):
6467**
drhf2f105d2012-08-20 15:53:54 +00006468** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006469** RESERVED_BYTE 0x40000001
6470** SHARED_RANGE 0x40000002 -> 0x40000200
6471**
6472** This works well on the local file system, but shows a nearly 100x
6473** slowdown in read performance on AFP because the AFP client disables
6474** the read cache when byte-range locks are present. Enabling the read
6475** cache exposes a cache coherency problem that is present on all OS X
6476** supported network file systems. NFS and AFP both observe the
6477** close-to-open semantics for ensuring cache coherency
6478** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6479** address the requirements for concurrent database access by multiple
6480** readers and writers
6481** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6482**
6483** To address the performance and cache coherency issues, proxy file locking
6484** changes the way database access is controlled by limiting access to a
6485** single host at a time and moving file locks off of the database file
6486** and onto a proxy file on the local file system.
6487**
6488**
6489** Using proxy locks
6490** -----------------
6491**
6492** C APIs
6493**
drh4bf66fd2015-02-19 02:43:02 +00006494** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006495** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006496** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6497** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006498**
6499**
6500** SQL pragmas
6501**
6502** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6503** PRAGMA [database.]lock_proxy_file
6504**
6505** Specifying ":auto:" means that if there is a conch file with a matching
6506** host ID in it, the proxy path in the conch file will be used, otherwise
6507** a proxy path based on the user's temp dir
6508** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6509** actual proxy file name is generated from the name and path of the
6510** database file. For example:
6511**
6512** For database path "/Users/me/foo.db"
6513** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6514**
6515** Once a lock proxy is configured for a database connection, it can not
6516** be removed, however it may be switched to a different proxy path via
6517** the above APIs (assuming the conch file is not being held by another
6518** connection or process).
6519**
6520**
6521** How proxy locking works
6522** -----------------------
6523**
6524** Proxy file locking relies primarily on two new supporting files:
6525**
6526** * conch file to limit access to the database file to a single host
6527** at a time
6528**
6529** * proxy file to act as a proxy for the advisory locks normally
6530** taken on the database
6531**
6532** The conch file - to use a proxy file, sqlite must first "hold the conch"
6533** by taking an sqlite-style shared lock on the conch file, reading the
6534** contents and comparing the host's unique host ID (see below) and lock
6535** proxy path against the values stored in the conch. The conch file is
6536** stored in the same directory as the database file and the file name
6537** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006538** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006539** host ID and/or proxy path, then the lock is escalated to an exclusive
6540** lock and the conch file contents is updated with the host ID and proxy
6541** path and the lock is downgraded to a shared lock again. If the conch
6542** is held by another process (with a shared lock), the exclusive lock
6543** will fail and SQLITE_BUSY is returned.
6544**
6545** The proxy file - a single-byte file used for all advisory file locks
6546** normally taken on the database file. This allows for safe sharing
6547** of the database file for multiple readers and writers on the same
6548** host (the conch ensures that they all use the same local lock file).
6549**
drh715ff302008-12-03 22:32:44 +00006550** Requesting the lock proxy does not immediately take the conch, it is
6551** only taken when the first request to lock database file is made.
6552** This matches the semantics of the traditional locking behavior, where
6553** opening a connection to a database file does not take a lock on it.
6554** The shared lock and an open file descriptor are maintained until
6555** the connection to the database is closed.
6556**
6557** The proxy file and the lock file are never deleted so they only need
6558** to be created the first time they are used.
6559**
6560** Configuration options
6561** ---------------------
6562**
6563** SQLITE_PREFER_PROXY_LOCKING
6564**
6565** Database files accessed on non-local file systems are
6566** automatically configured for proxy locking, lock files are
6567** named automatically using the same logic as
6568** PRAGMA lock_proxy_file=":auto:"
6569**
6570** SQLITE_PROXY_DEBUG
6571**
6572** Enables the logging of error messages during host id file
6573** retrieval and creation
6574**
drh715ff302008-12-03 22:32:44 +00006575** LOCKPROXYDIR
6576**
6577** Overrides the default directory used for lock proxy files that
6578** are named automatically via the ":auto:" setting
6579**
6580** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6581**
6582** Permissions to use when creating a directory for storing the
6583** lock proxy files, only used when LOCKPROXYDIR is not set.
6584**
6585**
6586** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6587** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6588** force proxy locking to be used for every database file opened, and 0
6589** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006590** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006591** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6592*/
6593
6594/*
6595** Proxy locking is only available on MacOSX
6596*/
drhd2cb50b2009-01-09 21:41:17 +00006597#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006598
drh715ff302008-12-03 22:32:44 +00006599/*
6600** The proxyLockingContext has the path and file structures for the remote
6601** and local proxy files in it
6602*/
6603typedef struct proxyLockingContext proxyLockingContext;
6604struct proxyLockingContext {
6605 unixFile *conchFile; /* Open conch file */
6606 char *conchFilePath; /* Name of the conch file */
6607 unixFile *lockProxy; /* Open proxy lock file */
6608 char *lockProxyPath; /* Name of the proxy lock file */
6609 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006610 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006611 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006612 void *oldLockingContext; /* Original lockingcontext to restore on close */
6613 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6614};
6615
drh7ed97b92010-01-20 13:07:21 +00006616/*
6617** The proxy lock file path for the database at dbPath is written into lPath,
6618** which must point to valid, writable memory large enough for a maxLen length
6619** file path.
drh715ff302008-12-03 22:32:44 +00006620*/
drh715ff302008-12-03 22:32:44 +00006621static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6622 int len;
6623 int dbLen;
6624 int i;
6625
6626#ifdef LOCKPROXYDIR
6627 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6628#else
6629# ifdef _CS_DARWIN_USER_TEMP_DIR
6630 {
drh7ed97b92010-01-20 13:07:21 +00006631 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006632 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006633 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006634 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006635 }
drh7ed97b92010-01-20 13:07:21 +00006636 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006637 }
6638# else
6639 len = strlcpy(lPath, "/tmp/", maxLen);
6640# endif
6641#endif
6642
6643 if( lPath[len-1]!='/' ){
6644 len = strlcat(lPath, "/", maxLen);
6645 }
6646
6647 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006648 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006649 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006650 char c = dbPath[i];
6651 lPath[i+len] = (c=='/')?'_':c;
6652 }
6653 lPath[i+len]='\0';
6654 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006655 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006656 return SQLITE_OK;
6657}
6658
drh7ed97b92010-01-20 13:07:21 +00006659/*
6660 ** Creates the lock file and any missing directories in lockPath
6661 */
6662static int proxyCreateLockPath(const char *lockPath){
6663 int i, len;
6664 char buf[MAXPATHLEN];
6665 int start = 0;
6666
6667 assert(lockPath!=NULL);
6668 /* try to create all the intermediate directories */
6669 len = (int)strlen(lockPath);
6670 buf[0] = lockPath[0];
6671 for( i=1; i<len; i++ ){
6672 if( lockPath[i] == '/' && (i - start > 0) ){
6673 /* only mkdir if leaf dir != "." or "/" or ".." */
6674 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6675 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6676 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006677 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006678 int err=errno;
6679 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006680 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006681 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006682 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006683 return err;
6684 }
6685 }
6686 }
6687 start=i+1;
6688 }
6689 buf[i] = lockPath[i];
6690 }
drh62aaa6c2015-11-21 17:27:42 +00006691 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006692 return 0;
6693}
6694
drh715ff302008-12-03 22:32:44 +00006695/*
6696** Create a new VFS file descriptor (stored in memory obtained from
6697** sqlite3_malloc) and open the file named "path" in the file descriptor.
6698**
6699** The caller is responsible not only for closing the file descriptor
6700** but also for freeing the memory associated with the file descriptor.
6701*/
drh7ed97b92010-01-20 13:07:21 +00006702static int proxyCreateUnixFile(
6703 const char *path, /* path for the new unixFile */
6704 unixFile **ppFile, /* unixFile created and returned by ref */
6705 int islockfile /* if non zero missing dirs will be created */
6706) {
6707 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006708 unixFile *pNew;
6709 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006710 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006711 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006712 int terrno = 0;
6713 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006714
drh7ed97b92010-01-20 13:07:21 +00006715 /* 1. first try to open/create the file
6716 ** 2. if that fails, and this is a lock file (not-conch), try creating
6717 ** the parent directories and then try again.
6718 ** 3. if that fails, try to open the file read-only
6719 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6720 */
6721 pUnused = findReusableFd(path, openFlags);
6722 if( pUnused ){
6723 fd = pUnused->fd;
6724 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006725 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006726 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006727 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006728 }
6729 }
6730 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006731 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006732 terrno = errno;
6733 if( fd<0 && errno==ENOENT && islockfile ){
6734 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006735 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006736 }
6737 }
6738 }
6739 if( fd<0 ){
6740 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006741 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006742 terrno = errno;
6743 }
6744 if( fd<0 ){
6745 if( islockfile ){
6746 return SQLITE_BUSY;
6747 }
6748 switch (terrno) {
6749 case EACCES:
6750 return SQLITE_PERM;
6751 case EIO:
6752 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6753 default:
drh9978c972010-02-23 17:36:32 +00006754 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006755 }
6756 }
6757
drhf3cdcdc2015-04-29 16:50:28 +00006758 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006759 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006760 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006761 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006762 }
6763 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006764 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006765 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006766 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006767 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006768 pUnused->fd = fd;
6769 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006770 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006771
drhc02a43a2012-01-10 23:18:38 +00006772 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006773 if( rc==SQLITE_OK ){
6774 *ppFile = pNew;
6775 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006776 }
drh7ed97b92010-01-20 13:07:21 +00006777end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006778 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006779 sqlite3_free(pNew);
6780 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006781 return rc;
6782}
6783
drh7ed97b92010-01-20 13:07:21 +00006784#ifdef SQLITE_TEST
6785/* simulate multiple hosts by creating unique hostid file paths */
6786int sqlite3_hostid_num = 0;
6787#endif
6788
6789#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6790
drh6bca6512015-04-13 23:05:28 +00006791#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006792/* Not always defined in the headers as it ought to be */
6793extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006794#endif
drh0ab216a2010-07-02 17:10:40 +00006795
drh7ed97b92010-01-20 13:07:21 +00006796/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6797** bytes of writable memory.
6798*/
6799static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006800 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6801 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006802#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006803 {
drh4bf66fd2015-02-19 02:43:02 +00006804 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006805 if( gethostuuid(pHostID, &timeout) ){
6806 int err = errno;
6807 if( pError ){
6808 *pError = err;
6809 }
6810 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006811 }
drh7ed97b92010-01-20 13:07:21 +00006812 }
drh3d4435b2011-08-26 20:55:50 +00006813#else
6814 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006815#endif
drh7ed97b92010-01-20 13:07:21 +00006816#ifdef SQLITE_TEST
6817 /* simulate multiple hosts by creating unique hostid file paths */
6818 if( sqlite3_hostid_num != 0){
6819 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6820 }
6821#endif
6822
6823 return SQLITE_OK;
6824}
6825
6826/* The conch file contains the header, host id and lock file path
6827 */
6828#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6829#define PROXY_HEADERLEN 1 /* conch file header length */
6830#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6831#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6832
6833/*
6834** Takes an open conch file, copies the contents to a new path and then moves
6835** it back. The newly created file's file descriptor is assigned to the
6836** conch file structure and finally the original conch file descriptor is
6837** closed. Returns zero if successful.
6838*/
6839static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6840 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6841 unixFile *conchFile = pCtx->conchFile;
6842 char tPath[MAXPATHLEN];
6843 char buf[PROXY_MAXCONCHLEN];
6844 char *cPath = pCtx->conchFilePath;
6845 size_t readLen = 0;
6846 size_t pathLen = 0;
6847 char errmsg[64] = "";
6848 int fd = -1;
6849 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006850 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006851
6852 /* create a new path by replace the trailing '-conch' with '-break' */
6853 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6854 if( pathLen>MAXPATHLEN || pathLen<6 ||
6855 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006856 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006857 goto end_breaklock;
6858 }
6859 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006860 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006861 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006862 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006863 goto end_breaklock;
6864 }
6865 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006866 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006867 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006868 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006869 goto end_breaklock;
6870 }
drhe562be52011-03-02 18:01:10 +00006871 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006872 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006873 goto end_breaklock;
6874 }
6875 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006876 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006877 goto end_breaklock;
6878 }
6879 rc = 0;
6880 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006881 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006882 conchFile->h = fd;
6883 conchFile->openFlags = O_RDWR | O_CREAT;
6884
6885end_breaklock:
6886 if( rc ){
6887 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006888 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006889 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006890 }
6891 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6892 }
6893 return rc;
6894}
6895
6896/* Take the requested lock on the conch file and break a stale lock if the
6897** host id matches.
6898*/
6899static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6900 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6901 unixFile *conchFile = pCtx->conchFile;
6902 int rc = SQLITE_OK;
6903 int nTries = 0;
6904 struct timespec conchModTime;
6905
drh3d4435b2011-08-26 20:55:50 +00006906 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006907 do {
6908 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6909 nTries ++;
6910 if( rc==SQLITE_BUSY ){
6911 /* If the lock failed (busy):
6912 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6913 * 2nd try: fail if the mod time changed or host id is different, wait
6914 * 10 sec and try again
6915 * 3rd try: break the lock unless the mod time has changed.
6916 */
6917 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006918 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006919 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006920 return SQLITE_IOERR_LOCK;
6921 }
6922
6923 if( nTries==1 ){
6924 conchModTime = buf.st_mtimespec;
6925 usleep(500000); /* wait 0.5 sec and try the lock again*/
6926 continue;
6927 }
6928
6929 assert( nTries>1 );
6930 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6931 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6932 return SQLITE_BUSY;
6933 }
6934
6935 if( nTries==2 ){
6936 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006937 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006938 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006939 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006940 return SQLITE_IOERR_LOCK;
6941 }
6942 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6943 /* don't break the lock if the host id doesn't match */
6944 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6945 return SQLITE_BUSY;
6946 }
6947 }else{
6948 /* don't break the lock on short read or a version mismatch */
6949 return SQLITE_BUSY;
6950 }
6951 usleep(10000000); /* wait 10 sec and try the lock again */
6952 continue;
6953 }
6954
6955 assert( nTries==3 );
6956 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6957 rc = SQLITE_OK;
6958 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006959 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006960 }
6961 if( !rc ){
6962 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6963 }
6964 }
6965 }
6966 } while( rc==SQLITE_BUSY && nTries<3 );
6967
6968 return rc;
6969}
6970
6971/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006972** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6973** lockPath means that the lockPath in the conch file will be used if the
6974** host IDs match, or a new lock path will be generated automatically
6975** and written to the conch file.
6976*/
6977static int proxyTakeConch(unixFile *pFile){
6978 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6979
drh7ed97b92010-01-20 13:07:21 +00006980 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006981 return SQLITE_OK;
6982 }else{
6983 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006984 uuid_t myHostID;
6985 int pError = 0;
6986 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006987 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006988 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006989 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006990 int createConch = 0;
6991 int hostIdMatch = 0;
6992 int readLen = 0;
6993 int tryOldLockPath = 0;
6994 int forceNewLockPath = 0;
6995
drh308c2a52010-05-14 11:30:18 +00006996 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006997 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006998 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006999
drh7ed97b92010-01-20 13:07:21 +00007000 rc = proxyGetHostID(myHostID, &pError);
7001 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007002 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007003 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007004 }
drh7ed97b92010-01-20 13:07:21 +00007005 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007006 if( rc!=SQLITE_OK ){
7007 goto end_takeconch;
7008 }
drh7ed97b92010-01-20 13:07:21 +00007009 /* read the existing conch file */
7010 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7011 if( readLen<0 ){
7012 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007013 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007014 rc = SQLITE_IOERR_READ;
7015 goto end_takeconch;
7016 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7017 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7018 /* a short read or version format mismatch means we need to create a new
7019 ** conch file.
7020 */
7021 createConch = 1;
7022 }
7023 /* if the host id matches and the lock path already exists in the conch
7024 ** we'll try to use the path there, if we can't open that path, we'll
7025 ** retry with a new auto-generated path
7026 */
7027 do { /* in case we need to try again for an :auto: named lock file */
7028
7029 if( !createConch && !forceNewLockPath ){
7030 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7031 PROXY_HOSTIDLEN);
7032 /* if the conch has data compare the contents */
7033 if( !pCtx->lockProxyPath ){
7034 /* for auto-named local lock file, just check the host ID and we'll
7035 ** use the local lock file path that's already in there
7036 */
7037 if( hostIdMatch ){
7038 size_t pathLen = (readLen - PROXY_PATHINDEX);
7039
7040 if( pathLen>=MAXPATHLEN ){
7041 pathLen=MAXPATHLEN-1;
7042 }
7043 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7044 lockPath[pathLen] = 0;
7045 tempLockPath = lockPath;
7046 tryOldLockPath = 1;
7047 /* create a copy of the lock path if the conch is taken */
7048 goto end_takeconch;
7049 }
7050 }else if( hostIdMatch
7051 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7052 readLen-PROXY_PATHINDEX)
7053 ){
7054 /* conch host and lock path match */
7055 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007056 }
drh7ed97b92010-01-20 13:07:21 +00007057 }
7058
7059 /* if the conch isn't writable and doesn't match, we can't take it */
7060 if( (conchFile->openFlags&O_RDWR) == 0 ){
7061 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007062 goto end_takeconch;
7063 }
drh7ed97b92010-01-20 13:07:21 +00007064
7065 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007066 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007067 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7068 tempLockPath = lockPath;
7069 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007070 }
drh7ed97b92010-01-20 13:07:21 +00007071
7072 /* update conch with host and path (this will fail if other process
7073 ** has a shared lock already), if the host id matches, use the big
7074 ** stick.
drh715ff302008-12-03 22:32:44 +00007075 */
drh7ed97b92010-01-20 13:07:21 +00007076 futimes(conchFile->h, NULL);
7077 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007078 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007079 /* We are trying for an exclusive lock but another thread in this
7080 ** same process is still holding a shared lock. */
7081 rc = SQLITE_BUSY;
7082 } else {
7083 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007084 }
drh715ff302008-12-03 22:32:44 +00007085 }else{
drh4bf66fd2015-02-19 02:43:02 +00007086 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007087 }
drh7ed97b92010-01-20 13:07:21 +00007088 if( rc==SQLITE_OK ){
7089 char writeBuffer[PROXY_MAXCONCHLEN];
7090 int writeSize = 0;
7091
7092 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7093 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7094 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007095 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7096 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007097 }else{
7098 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7099 }
7100 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007101 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007102 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007103 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007104 /* If we created a new conch file (not just updated the contents of a
7105 ** valid conch file), try to match the permissions of the database
7106 */
7107 if( rc==SQLITE_OK && createConch ){
7108 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007109 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007110 if( err==0 ){
7111 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7112 S_IROTH|S_IWOTH);
7113 /* try to match the database file R/W permissions, ignore failure */
7114#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007115 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007116#else
drhff812312011-02-23 13:33:46 +00007117 do{
drhe562be52011-03-02 18:01:10 +00007118 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007119 }while( rc==(-1) && errno==EINTR );
7120 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007121 int code = errno;
7122 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7123 cmode, code, strerror(code));
7124 } else {
7125 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7126 }
7127 }else{
7128 int code = errno;
7129 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7130 err, code, strerror(code));
7131#endif
7132 }
drh715ff302008-12-03 22:32:44 +00007133 }
7134 }
drh7ed97b92010-01-20 13:07:21 +00007135 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7136
7137 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007138 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007139 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007140 int fd;
drh7ed97b92010-01-20 13:07:21 +00007141 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007142 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007143 }
7144 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007145 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007146 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007147 if( fd>=0 ){
7148 pFile->h = fd;
7149 }else{
drh9978c972010-02-23 17:36:32 +00007150 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007151 during locking */
7152 }
7153 }
7154 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7155 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7156 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7157 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7158 /* we couldn't create the proxy lock file with the old lock file path
7159 ** so try again via auto-naming
7160 */
7161 forceNewLockPath = 1;
7162 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007163 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007164 }
7165 }
7166 if( rc==SQLITE_OK ){
7167 /* Need to make a copy of path if we extracted the value
7168 ** from the conch file or the path was allocated on the stack
7169 */
7170 if( tempLockPath ){
7171 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7172 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007173 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007174 }
7175 }
7176 }
7177 if( rc==SQLITE_OK ){
7178 pCtx->conchHeld = 1;
7179
7180 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7181 afpLockingContext *afpCtx;
7182 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7183 afpCtx->dbPath = pCtx->lockProxyPath;
7184 }
7185 } else {
7186 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7187 }
drh308c2a52010-05-14 11:30:18 +00007188 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7189 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007190 return rc;
drh308c2a52010-05-14 11:30:18 +00007191 } while (1); /* in case we need to retry the :auto: lock file -
7192 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007193 }
7194}
7195
7196/*
7197** If pFile holds a lock on a conch file, then release that lock.
7198*/
7199static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007200 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007201 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7202 unixFile *conchFile; /* Name of the conch file */
7203
7204 pCtx = (proxyLockingContext *)pFile->lockingContext;
7205 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007206 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007207 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007208 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007209 if( pCtx->conchHeld>0 ){
7210 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7211 }
drh715ff302008-12-03 22:32:44 +00007212 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007213 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7214 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007215 return rc;
7216}
7217
7218/*
7219** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007220** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007221** Make *pConchPath point to the new name. Return SQLITE_OK on success
7222** or SQLITE_NOMEM if unable to obtain memory.
7223**
7224** The caller is responsible for ensuring that the allocated memory
7225** space is eventually freed.
7226**
7227** *pConchPath is set to NULL if a memory allocation error occurs.
7228*/
7229static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7230 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007231 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007232 char *conchPath; /* buffer in which to construct conch name */
7233
7234 /* Allocate space for the conch filename and initialize the name to
7235 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007236 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007237 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007238 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007239 }
7240 memcpy(conchPath, dbPath, len+1);
7241
7242 /* now insert a "." before the last / character */
7243 for( i=(len-1); i>=0; i-- ){
7244 if( conchPath[i]=='/' ){
7245 i++;
7246 break;
7247 }
7248 }
7249 conchPath[i]='.';
7250 while ( i<len ){
7251 conchPath[i+1]=dbPath[i];
7252 i++;
7253 }
7254
7255 /* append the "-conch" suffix to the file */
7256 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007257 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007258
7259 return SQLITE_OK;
7260}
7261
7262
7263/* Takes a fully configured proxy locking-style unix file and switches
7264** the local lock file path
7265*/
7266static int switchLockProxyPath(unixFile *pFile, const char *path) {
7267 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7268 char *oldPath = pCtx->lockProxyPath;
7269 int rc = SQLITE_OK;
7270
drh308c2a52010-05-14 11:30:18 +00007271 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007272 return SQLITE_BUSY;
7273 }
7274
7275 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7276 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7277 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7278 return SQLITE_OK;
7279 }else{
7280 unixFile *lockProxy = pCtx->lockProxy;
7281 pCtx->lockProxy=NULL;
7282 pCtx->conchHeld = 0;
7283 if( lockProxy!=NULL ){
7284 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7285 if( rc ) return rc;
7286 sqlite3_free(lockProxy);
7287 }
7288 sqlite3_free(oldPath);
7289 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7290 }
7291
7292 return rc;
7293}
7294
7295/*
7296** pFile is a file that has been opened by a prior xOpen call. dbPath
7297** is a string buffer at least MAXPATHLEN+1 characters in size.
7298**
7299** This routine find the filename associated with pFile and writes it
7300** int dbPath.
7301*/
7302static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007303#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007304 if( pFile->pMethod == &afpIoMethods ){
7305 /* afp style keeps a reference to the db path in the filePath field
7306 ** of the struct */
drhea678832008-12-10 19:26:22 +00007307 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007308 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7309 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007310 } else
drh715ff302008-12-03 22:32:44 +00007311#endif
7312 if( pFile->pMethod == &dotlockIoMethods ){
7313 /* dot lock style uses the locking context to store the dot lock
7314 ** file path */
7315 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7316 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7317 }else{
7318 /* all other styles use the locking context to store the db file path */
7319 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007320 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007321 }
7322 return SQLITE_OK;
7323}
7324
7325/*
7326** Takes an already filled in unix file and alters it so all file locking
7327** will be performed on the local proxy lock file. The following fields
7328** are preserved in the locking context so that they can be restored and
7329** the unix structure properly cleaned up at close time:
7330** ->lockingContext
7331** ->pMethod
7332*/
7333static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7334 proxyLockingContext *pCtx;
7335 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7336 char *lockPath=NULL;
7337 int rc = SQLITE_OK;
7338
drh308c2a52010-05-14 11:30:18 +00007339 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007340 return SQLITE_BUSY;
7341 }
7342 proxyGetDbPathForUnixFile(pFile, dbPath);
7343 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7344 lockPath=NULL;
7345 }else{
7346 lockPath=(char *)path;
7347 }
7348
drh308c2a52010-05-14 11:30:18 +00007349 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007350 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007351
drhf3cdcdc2015-04-29 16:50:28 +00007352 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007353 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007354 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007355 }
7356 memset(pCtx, 0, sizeof(*pCtx));
7357
7358 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7359 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007360 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7361 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7362 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7363 ** (c) the file system is read-only, then enable no-locking access.
7364 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7365 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7366 */
7367 struct statfs fsInfo;
7368 struct stat conchInfo;
7369 int goLockless = 0;
7370
drh99ab3b12011-03-02 15:09:07 +00007371 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007372 int err = errno;
7373 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7374 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7375 }
7376 }
7377 if( goLockless ){
7378 pCtx->conchHeld = -1; /* read only FS/ lockless */
7379 rc = SQLITE_OK;
7380 }
7381 }
drh715ff302008-12-03 22:32:44 +00007382 }
7383 if( rc==SQLITE_OK && lockPath ){
7384 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7385 }
7386
7387 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007388 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7389 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007390 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007391 }
7392 }
7393 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007394 /* all memory is allocated, proxys are created and assigned,
7395 ** switch the locking context and pMethod then return.
7396 */
drh715ff302008-12-03 22:32:44 +00007397 pCtx->oldLockingContext = pFile->lockingContext;
7398 pFile->lockingContext = pCtx;
7399 pCtx->pOldMethod = pFile->pMethod;
7400 pFile->pMethod = &proxyIoMethods;
7401 }else{
7402 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007403 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007404 sqlite3_free(pCtx->conchFile);
7405 }
drhd56b1212010-08-11 06:14:15 +00007406 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007407 sqlite3_free(pCtx->conchFilePath);
7408 sqlite3_free(pCtx);
7409 }
drh308c2a52010-05-14 11:30:18 +00007410 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7411 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007412 return rc;
7413}
7414
7415
7416/*
7417** This routine handles sqlite3_file_control() calls that are specific
7418** to proxy locking.
7419*/
7420static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7421 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007422 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007423 unixFile *pFile = (unixFile*)id;
7424 if( pFile->pMethod == &proxyIoMethods ){
7425 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7426 proxyTakeConch(pFile);
7427 if( pCtx->lockProxyPath ){
7428 *(const char **)pArg = pCtx->lockProxyPath;
7429 }else{
7430 *(const char **)pArg = ":auto: (not held)";
7431 }
7432 } else {
7433 *(const char **)pArg = NULL;
7434 }
7435 return SQLITE_OK;
7436 }
drh4bf66fd2015-02-19 02:43:02 +00007437 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007438 unixFile *pFile = (unixFile*)id;
7439 int rc = SQLITE_OK;
7440 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7441 if( pArg==NULL || (const char *)pArg==0 ){
7442 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007443 /* turn off proxy locking - not supported. If support is added for
7444 ** switching proxy locking mode off then it will need to fail if
7445 ** the journal mode is WAL mode.
7446 */
drh715ff302008-12-03 22:32:44 +00007447 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7448 }else{
7449 /* turn off proxy locking - already off - NOOP */
7450 rc = SQLITE_OK;
7451 }
7452 }else{
7453 const char *proxyPath = (const char *)pArg;
7454 if( isProxyStyle ){
7455 proxyLockingContext *pCtx =
7456 (proxyLockingContext*)pFile->lockingContext;
7457 if( !strcmp(pArg, ":auto:")
7458 || (pCtx->lockProxyPath &&
7459 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7460 ){
7461 rc = SQLITE_OK;
7462 }else{
7463 rc = switchLockProxyPath(pFile, proxyPath);
7464 }
7465 }else{
7466 /* turn on proxy file locking */
7467 rc = proxyTransformUnixFile(pFile, proxyPath);
7468 }
7469 }
7470 return rc;
7471 }
7472 default: {
7473 assert( 0 ); /* The call assures that only valid opcodes are sent */
7474 }
7475 }
7476 /*NOTREACHED*/
7477 return SQLITE_ERROR;
7478}
7479
7480/*
7481** Within this division (the proxying locking implementation) the procedures
7482** above this point are all utilities. The lock-related methods of the
7483** proxy-locking sqlite3_io_method object follow.
7484*/
7485
7486
7487/*
7488** This routine checks if there is a RESERVED lock held on the specified
7489** file by this or any other process. If such a lock is held, set *pResOut
7490** to a non-zero value otherwise *pResOut is set to zero. The return value
7491** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7492*/
7493static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7494 unixFile *pFile = (unixFile*)id;
7495 int rc = proxyTakeConch(pFile);
7496 if( rc==SQLITE_OK ){
7497 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007498 if( pCtx->conchHeld>0 ){
7499 unixFile *proxy = pCtx->lockProxy;
7500 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7501 }else{ /* conchHeld < 0 is lockless */
7502 pResOut=0;
7503 }
drh715ff302008-12-03 22:32:44 +00007504 }
7505 return rc;
7506}
7507
7508/*
drh308c2a52010-05-14 11:30:18 +00007509** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007510** of the following:
7511**
7512** (1) SHARED_LOCK
7513** (2) RESERVED_LOCK
7514** (3) PENDING_LOCK
7515** (4) EXCLUSIVE_LOCK
7516**
7517** Sometimes when requesting one lock state, additional lock states
7518** are inserted in between. The locking might fail on one of the later
7519** transitions leaving the lock state different from what it started but
7520** still short of its goal. The following chart shows the allowed
7521** transitions and the inserted intermediate states:
7522**
7523** UNLOCKED -> SHARED
7524** SHARED -> RESERVED
7525** SHARED -> (PENDING) -> EXCLUSIVE
7526** RESERVED -> (PENDING) -> EXCLUSIVE
7527** PENDING -> EXCLUSIVE
7528**
7529** This routine will only increase a lock. Use the sqlite3OsUnlock()
7530** routine to lower a locking level.
7531*/
drh308c2a52010-05-14 11:30:18 +00007532static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007533 unixFile *pFile = (unixFile*)id;
7534 int rc = proxyTakeConch(pFile);
7535 if( rc==SQLITE_OK ){
7536 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007537 if( pCtx->conchHeld>0 ){
7538 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007539 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7540 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007541 }else{
7542 /* conchHeld < 0 is lockless */
7543 }
drh715ff302008-12-03 22:32:44 +00007544 }
7545 return rc;
7546}
7547
7548
7549/*
drh308c2a52010-05-14 11:30:18 +00007550** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007551** must be either NO_LOCK or SHARED_LOCK.
7552**
7553** If the locking level of the file descriptor is already at or below
7554** the requested locking level, this routine is a no-op.
7555*/
drh308c2a52010-05-14 11:30:18 +00007556static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007557 unixFile *pFile = (unixFile*)id;
7558 int rc = proxyTakeConch(pFile);
7559 if( rc==SQLITE_OK ){
7560 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007561 if( pCtx->conchHeld>0 ){
7562 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007563 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7564 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007565 }else{
7566 /* conchHeld < 0 is lockless */
7567 }
drh715ff302008-12-03 22:32:44 +00007568 }
7569 return rc;
7570}
7571
7572/*
7573** Close a file that uses proxy locks.
7574*/
7575static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007576 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007577 unixFile *pFile = (unixFile*)id;
7578 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7579 unixFile *lockProxy = pCtx->lockProxy;
7580 unixFile *conchFile = pCtx->conchFile;
7581 int rc = SQLITE_OK;
7582
7583 if( lockProxy ){
7584 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7585 if( rc ) return rc;
7586 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7587 if( rc ) return rc;
7588 sqlite3_free(lockProxy);
7589 pCtx->lockProxy = 0;
7590 }
7591 if( conchFile ){
7592 if( pCtx->conchHeld ){
7593 rc = proxyReleaseConch(pFile);
7594 if( rc ) return rc;
7595 }
7596 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7597 if( rc ) return rc;
7598 sqlite3_free(conchFile);
7599 }
drhd56b1212010-08-11 06:14:15 +00007600 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007601 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007602 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007603 /* restore the original locking context and pMethod then close it */
7604 pFile->lockingContext = pCtx->oldLockingContext;
7605 pFile->pMethod = pCtx->pOldMethod;
7606 sqlite3_free(pCtx);
7607 return pFile->pMethod->xClose(id);
7608 }
7609 return SQLITE_OK;
7610}
7611
7612
7613
drhd2cb50b2009-01-09 21:41:17 +00007614#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007615/*
7616** The proxy locking style is intended for use with AFP filesystems.
7617** And since AFP is only supported on MacOSX, the proxy locking is also
7618** restricted to MacOSX.
7619**
7620**
7621******************* End of the proxy lock implementation **********************
7622******************************************************************************/
7623
drh734c9862008-11-28 15:37:20 +00007624/*
danielk1977e339d652008-06-28 11:23:00 +00007625** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007626**
7627** This routine registers all VFS implementations for unix-like operating
7628** systems. This routine, and the sqlite3_os_end() routine that follows,
7629** should be the only routines in this file that are visible from other
7630** files.
drh6b9d6dd2008-12-03 19:34:47 +00007631**
7632** This routine is called once during SQLite initialization and by a
7633** single thread. The memory allocation and mutex subsystems have not
7634** necessarily been initialized when this routine is called, and so they
7635** should not be used.
drh153c62c2007-08-24 03:51:33 +00007636*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007637int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007638 /*
7639 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007640 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7641 ** to the "finder" function. (pAppData is a pointer to a pointer because
7642 ** silly C90 rules prohibit a void* from being cast to a function pointer
7643 ** and so we have to go through the intermediate pointer to avoid problems
7644 ** when compiling with -pedantic-errors on GCC.)
7645 **
7646 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007647 ** finder-function. The finder-function returns a pointer to the
7648 ** sqlite_io_methods object that implements the desired locking
7649 ** behaviors. See the division above that contains the IOMETHODS
7650 ** macro for addition information on finder-functions.
7651 **
7652 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7653 ** object. But the "autolockIoFinder" available on MacOSX does a little
7654 ** more than that; it looks at the filesystem type that hosts the
7655 ** database file and tries to choose an locking method appropriate for
7656 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007657 */
drh7708e972008-11-29 00:56:52 +00007658 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007659 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007660 sizeof(unixFile), /* szOsFile */ \
7661 MAX_PATHNAME, /* mxPathname */ \
7662 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007663 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007664 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007665 unixOpen, /* xOpen */ \
7666 unixDelete, /* xDelete */ \
7667 unixAccess, /* xAccess */ \
7668 unixFullPathname, /* xFullPathname */ \
7669 unixDlOpen, /* xDlOpen */ \
7670 unixDlError, /* xDlError */ \
7671 unixDlSym, /* xDlSym */ \
7672 unixDlClose, /* xDlClose */ \
7673 unixRandomness, /* xRandomness */ \
7674 unixSleep, /* xSleep */ \
7675 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007676 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007677 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007678 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007679 unixGetSystemCall, /* xGetSystemCall */ \
7680 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007681 }
7682
drh6b9d6dd2008-12-03 19:34:47 +00007683 /*
7684 ** All default VFSes for unix are contained in the following array.
7685 **
7686 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7687 ** by the SQLite core when the VFS is registered. So the following
7688 ** array cannot be const.
7689 */
danielk1977e339d652008-06-28 11:23:00 +00007690 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007691#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007692 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007693#elif OS_VXWORKS
7694 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007695#else
7696 UNIXVFS("unix", posixIoFinder ),
7697#endif
7698 UNIXVFS("unix-none", nolockIoFinder ),
7699 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007700 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007701#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007702 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007703#endif
drhe89b2912015-03-03 20:42:01 +00007704#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007705 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007706#endif
drhe89b2912015-03-03 20:42:01 +00007707#if SQLITE_ENABLE_LOCKING_STYLE
7708 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007709#endif
drhd2cb50b2009-01-09 21:41:17 +00007710#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007711 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007712 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007713 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007714#endif
drh153c62c2007-08-24 03:51:33 +00007715 };
drh6b9d6dd2008-12-03 19:34:47 +00007716 unsigned int i; /* Loop counter */
7717
drh2aa5a002011-04-13 13:42:25 +00007718 /* Double-check that the aSyscall[] array has been constructed
7719 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007720 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007721
drh6b9d6dd2008-12-03 19:34:47 +00007722 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007723 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007724 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007725 }
drh56115892018-02-05 16:39:12 +00007726 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
danielk1977c0fa4c52008-06-25 17:19:00 +00007727 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007728}
danielk1977e339d652008-06-28 11:23:00 +00007729
7730/*
drh6b9d6dd2008-12-03 19:34:47 +00007731** Shutdown the operating system interface.
7732**
7733** Some operating systems might need to do some cleanup in this routine,
7734** to release dynamically allocated objects. But not on unix.
7735** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007736*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007737int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00007738 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00007739 return SQLITE_OK;
7740}
drhdce8bdb2007-08-16 13:01:44 +00007741
danielk197729bafea2008-06-26 10:41:19 +00007742#endif /* SQLITE_OS_UNIX */