blob: b94d417f4938178fb28ba6e3d853448f3b71793b [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
drh6226ca22015-11-24 15:06:28 +0000471 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
472#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
473
dan4dd51442013-08-26 14:30:25 +0000474#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000475 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
476#else
477 { "mmap", (sqlite3_syscall_ptr)0, 0 },
478#endif
drh6226ca22015-11-24 15:06:28 +0000479#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000480
drhe4a08f92016-01-08 19:17:30 +0000481#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000482 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000483#else
drha8299922016-01-08 22:31:00 +0000484 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000485#endif
drh6226ca22015-11-24 15:06:28 +0000486#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000487
drhe4a08f92016-01-08 19:17:30 +0000488#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000489 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
490#else
491 { "mremap", (sqlite3_syscall_ptr)0, 0 },
492#endif
drh6226ca22015-11-24 15:06:28 +0000493#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
494
drh24dbeae2016-01-08 22:18:00 +0000495#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000496 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000497#else
498 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
499#endif
drh6226ca22015-11-24 15:06:28 +0000500#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000501
drhe2258a22016-01-12 00:37:55 +0000502#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000503 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000504#else
505 { "readlink", (sqlite3_syscall_ptr)0, 0 },
506#endif
drh6226ca22015-11-24 15:06:28 +0000507#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000508
danaf1b36b2016-01-25 18:43:05 +0000509#if defined(HAVE_LSTAT)
510 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
511#else
512 { "lstat", (sqlite3_syscall_ptr)0, 0 },
513#endif
dancaf6b152016-01-25 18:05:49 +0000514#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000515
drhb5d013e2017-10-25 16:14:12 +0000516#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +0000517 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
drhb5d013e2017-10-25 16:14:12 +0000518#else
519 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
520#endif
dan9d709542017-07-21 21:06:24 +0000521#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
danefe16972017-07-20 19:49:14 +0000522
drhe562be52011-03-02 18:01:10 +0000523}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000524
drh6226ca22015-11-24 15:06:28 +0000525
526/*
527** On some systems, calls to fchown() will trigger a message in a security
528** log if they come from non-root processes. So avoid calling fchown() if
529** we are not running as root.
530*/
531static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000532#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000533 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000534#else
535 return 0;
drh6226ca22015-11-24 15:06:28 +0000536#endif
537}
538
drh99ab3b12011-03-02 15:09:07 +0000539/*
540** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000541** "unix" VFSes. Return SQLITE_OK opon successfully updating the
542** system call pointer, or SQLITE_NOTFOUND if there is no configurable
543** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000544*/
545static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000546 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
547 const char *zName, /* Name of system call to override */
548 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000549){
drh58ad5802011-03-23 22:02:23 +0000550 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000551 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000552
553 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000554 if( zName==0 ){
555 /* If no zName is given, restore all system calls to their default
556 ** settings and return NULL
557 */
dan51438a72011-04-02 17:00:47 +0000558 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000559 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
560 if( aSyscall[i].pDefault ){
561 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000562 }
563 }
564 }else{
565 /* If zName is specified, operate on only the one system call
566 ** specified.
567 */
568 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
569 if( strcmp(zName, aSyscall[i].zName)==0 ){
570 if( aSyscall[i].pDefault==0 ){
571 aSyscall[i].pDefault = aSyscall[i].pCurrent;
572 }
drh1df30962011-03-02 19:06:42 +0000573 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000574 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
575 aSyscall[i].pCurrent = pNewFunc;
576 break;
577 }
578 }
579 }
580 return rc;
581}
582
drh1df30962011-03-02 19:06:42 +0000583/*
584** Return the value of a system call. Return NULL if zName is not a
585** recognized system call name. NULL is also returned if the system call
586** is currently undefined.
587*/
drh58ad5802011-03-23 22:02:23 +0000588static sqlite3_syscall_ptr unixGetSystemCall(
589 sqlite3_vfs *pNotUsed,
590 const char *zName
591){
592 unsigned int i;
593
594 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000595 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
596 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
597 }
598 return 0;
599}
600
601/*
602** Return the name of the first system call after zName. If zName==NULL
603** then return the name of the first system call. Return NULL if zName
604** is the last system call or if zName is not the name of a valid
605** system call.
606*/
607static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000608 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000609
610 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000611 if( zName ){
612 for(i=0; i<ArraySize(aSyscall)-1; i++){
613 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000614 }
615 }
dan0fd7d862011-03-29 10:04:23 +0000616 for(i++; i<ArraySize(aSyscall); i++){
617 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000618 }
619 return 0;
620}
621
drhad4f1e52011-03-04 15:43:57 +0000622/*
drh77a3fdc2013-08-30 14:24:12 +0000623** Do not accept any file descriptor less than this value, in order to avoid
624** opening database file using file descriptors that are commonly used for
625** standard input, output, and error.
626*/
627#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
628# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
629#endif
630
631/*
drh8c815d12012-02-13 20:16:37 +0000632** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000633** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000634**
635** If the file creation mode "m" is 0 then set it to the default for
636** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
637** 0644) as modified by the system umask. If m is not 0, then
638** make the file creation mode be exactly m ignoring the umask.
639**
640** The m parameter will be non-zero only when creating -wal, -journal,
641** and -shm files. We want those files to have *exactly* the same
642** permissions as their original database, unadulterated by the umask.
643** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
644** transaction crashes and leaves behind hot journals, then any
645** process that is able to write to the database will also be able to
646** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000647*/
drh8c815d12012-02-13 20:16:37 +0000648static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000649 int fd;
drhe1186ab2013-01-04 20:45:13 +0000650 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000651 while(1){
drh5adc60b2012-04-14 13:25:11 +0000652#if defined(O_CLOEXEC)
653 fd = osOpen(z,f|O_CLOEXEC,m2);
654#else
655 fd = osOpen(z,f,m2);
656#endif
drh5128d002013-08-30 06:20:23 +0000657 if( fd<0 ){
658 if( errno==EINTR ) continue;
659 break;
660 }
drh77a3fdc2013-08-30 14:24:12 +0000661 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000662 osClose(fd);
663 sqlite3_log(SQLITE_WARNING,
664 "attempt to open \"%s\" as file descriptor %d", z, fd);
665 fd = -1;
666 if( osOpen("/dev/null", f, m)<0 ) break;
667 }
drhe1186ab2013-01-04 20:45:13 +0000668 if( fd>=0 ){
669 if( m!=0 ){
670 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000671 if( osFstat(fd, &statbuf)==0
672 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000673 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000674 ){
drhe1186ab2013-01-04 20:45:13 +0000675 osFchmod(fd, m);
676 }
677 }
drh5adc60b2012-04-14 13:25:11 +0000678#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000679 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000680#endif
drhe1186ab2013-01-04 20:45:13 +0000681 }
drh5adc60b2012-04-14 13:25:11 +0000682 return fd;
drhad4f1e52011-03-04 15:43:57 +0000683}
danielk197713adf8a2004-06-03 16:08:41 +0000684
drh107886a2008-11-21 22:21:50 +0000685/*
dan9359c7b2009-08-21 08:29:10 +0000686** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000687** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000688** vxworksFileId objects used by this file, all of which may be
689** shared by multiple threads.
690**
691** Function unixMutexHeld() is used to assert() that the global mutex
692** is held when required. This function is only used as part of assert()
693** statements. e.g.
694**
695** unixEnterMutex()
696** assert( unixMutexHeld() );
697** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000698*/
699static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000700 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000701}
702static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000703 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000704}
dan9359c7b2009-08-21 08:29:10 +0000705#ifdef SQLITE_DEBUG
706static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000707 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000708}
709#endif
drh107886a2008-11-21 22:21:50 +0000710
drh734c9862008-11-28 15:37:20 +0000711
mistachkinfb383e92015-04-16 03:24:38 +0000712#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000713/*
714** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000715** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000716** integer lock-type.
717*/
drh308c2a52010-05-14 11:30:18 +0000718static const char *azFileLock(int eFileLock){
719 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000720 case NO_LOCK: return "NONE";
721 case SHARED_LOCK: return "SHARED";
722 case RESERVED_LOCK: return "RESERVED";
723 case PENDING_LOCK: return "PENDING";
724 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000725 }
726 return "ERROR";
727}
728#endif
729
730#ifdef SQLITE_LOCK_TRACE
731/*
732** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000733**
drh734c9862008-11-28 15:37:20 +0000734** This routine is used for troubleshooting locks on multithreaded
735** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
736** command-line option on the compiler. This code is normally
737** turned off.
738*/
739static int lockTrace(int fd, int op, struct flock *p){
740 char *zOpName, *zType;
741 int s;
742 int savedErrno;
743 if( op==F_GETLK ){
744 zOpName = "GETLK";
745 }else if( op==F_SETLK ){
746 zOpName = "SETLK";
747 }else{
drh99ab3b12011-03-02 15:09:07 +0000748 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000749 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
750 return s;
751 }
752 if( p->l_type==F_RDLCK ){
753 zType = "RDLCK";
754 }else if( p->l_type==F_WRLCK ){
755 zType = "WRLCK";
756 }else if( p->l_type==F_UNLCK ){
757 zType = "UNLCK";
758 }else{
759 assert( 0 );
760 }
761 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000762 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000763 savedErrno = errno;
764 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
765 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
766 (int)p->l_pid, s);
767 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
768 struct flock l2;
769 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000770 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000771 if( l2.l_type==F_RDLCK ){
772 zType = "RDLCK";
773 }else if( l2.l_type==F_WRLCK ){
774 zType = "WRLCK";
775 }else if( l2.l_type==F_UNLCK ){
776 zType = "UNLCK";
777 }else{
778 assert( 0 );
779 }
780 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
781 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
782 }
783 errno = savedErrno;
784 return s;
785}
drh99ab3b12011-03-02 15:09:07 +0000786#undef osFcntl
787#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000788#endif /* SQLITE_LOCK_TRACE */
789
drhff812312011-02-23 13:33:46 +0000790/*
791** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000792**
drhe6d41732015-02-21 00:49:00 +0000793** All calls to ftruncate() within this file should be made through
794** this wrapper. On the Android platform, bypassing the logic below
795** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000796*/
drhff812312011-02-23 13:33:46 +0000797static int robust_ftruncate(int h, sqlite3_int64 sz){
798 int rc;
dan2ee53412014-09-06 16:49:40 +0000799#ifdef __ANDROID__
800 /* On Android, ftruncate() always uses 32-bit offsets, even if
801 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000802 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000803 ** such attempts. */
804 if( sz>(sqlite3_int64)0x7FFFFFFF ){
805 rc = SQLITE_OK;
806 }else
807#endif
drh99ab3b12011-03-02 15:09:07 +0000808 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000809 return rc;
810}
drh734c9862008-11-28 15:37:20 +0000811
812/*
813** This routine translates a standard POSIX errno code into something
814** useful to the clients of the sqlite3 functions. Specifically, it is
815** intended to translate a variety of "try again" errors into SQLITE_BUSY
816** and a variety of "please close the file descriptor NOW" errors into
817** SQLITE_IOERR
818**
819** Errors during initialization of locks, or file system support for locks,
820** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
821*/
822static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000823 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
824 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
825 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
826 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000827 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000828 case EACCES:
drh734c9862008-11-28 15:37:20 +0000829 case EAGAIN:
830 case ETIMEDOUT:
831 case EBUSY:
832 case EINTR:
833 case ENOLCK:
834 /* random NFS retry error, unless during file system support
835 * introspection, in which it actually means what it says */
836 return SQLITE_BUSY;
837
drh734c9862008-11-28 15:37:20 +0000838 case EPERM:
839 return SQLITE_PERM;
840
drh734c9862008-11-28 15:37:20 +0000841 default:
842 return sqliteIOErr;
843 }
844}
845
846
drh734c9862008-11-28 15:37:20 +0000847/******************************************************************************
848****************** Begin Unique File ID Utility Used By VxWorks ***************
849**
850** On most versions of unix, we can get a unique ID for a file by concatenating
851** the device number and the inode number. But this does not work on VxWorks.
852** On VxWorks, a unique file id must be based on the canonical filename.
853**
854** A pointer to an instance of the following structure can be used as a
855** unique file ID in VxWorks. Each instance of this structure contains
856** a copy of the canonical filename. There is also a reference count.
857** The structure is reclaimed when the number of pointers to it drops to
858** zero.
859**
860** There are never very many files open at one time and lookups are not
861** a performance-critical path, so it is sufficient to put these
862** structures on a linked list.
863*/
864struct vxworksFileId {
865 struct vxworksFileId *pNext; /* Next in a list of them all */
866 int nRef; /* Number of references to this one */
867 int nName; /* Length of the zCanonicalName[] string */
868 char *zCanonicalName; /* Canonical filename */
869};
870
871#if OS_VXWORKS
872/*
drh9b35ea62008-11-29 02:20:26 +0000873** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000874** variable:
875*/
876static struct vxworksFileId *vxworksFileList = 0;
877
878/*
879** Simplify a filename into its canonical form
880** by making the following changes:
881**
882** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000883** * convert /./ into just /
884** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000885**
886** Changes are made in-place. Return the new name length.
887**
888** The original filename is in z[0..n-1]. Return the number of
889** characters in the simplified name.
890*/
891static int vxworksSimplifyName(char *z, int n){
892 int i, j;
893 while( n>1 && z[n-1]=='/' ){ n--; }
894 for(i=j=0; i<n; i++){
895 if( z[i]=='/' ){
896 if( z[i+1]=='/' ) continue;
897 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
898 i += 1;
899 continue;
900 }
901 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
902 while( j>0 && z[j-1]!='/' ){ j--; }
903 if( j>0 ){ j--; }
904 i += 2;
905 continue;
906 }
907 }
908 z[j++] = z[i];
909 }
910 z[j] = 0;
911 return j;
912}
913
914/*
915** Find a unique file ID for the given absolute pathname. Return
916** a pointer to the vxworksFileId object. This pointer is the unique
917** file ID.
918**
919** The nRef field of the vxworksFileId object is incremented before
920** the object is returned. A new vxworksFileId object is created
921** and added to the global list if necessary.
922**
923** If a memory allocation error occurs, return NULL.
924*/
925static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
926 struct vxworksFileId *pNew; /* search key and new file ID */
927 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
928 int n; /* Length of zAbsoluteName string */
929
930 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000931 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000932 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000933 if( pNew==0 ) return 0;
934 pNew->zCanonicalName = (char*)&pNew[1];
935 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
936 n = vxworksSimplifyName(pNew->zCanonicalName, n);
937
938 /* Search for an existing entry that matching the canonical name.
939 ** If found, increment the reference count and return a pointer to
940 ** the existing file ID.
941 */
942 unixEnterMutex();
943 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
944 if( pCandidate->nName==n
945 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
946 ){
947 sqlite3_free(pNew);
948 pCandidate->nRef++;
949 unixLeaveMutex();
950 return pCandidate;
951 }
952 }
953
954 /* No match was found. We will make a new file ID */
955 pNew->nRef = 1;
956 pNew->nName = n;
957 pNew->pNext = vxworksFileList;
958 vxworksFileList = pNew;
959 unixLeaveMutex();
960 return pNew;
961}
962
963/*
964** Decrement the reference count on a vxworksFileId object. Free
965** the object when the reference count reaches zero.
966*/
967static void vxworksReleaseFileId(struct vxworksFileId *pId){
968 unixEnterMutex();
969 assert( pId->nRef>0 );
970 pId->nRef--;
971 if( pId->nRef==0 ){
972 struct vxworksFileId **pp;
973 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
974 assert( *pp==pId );
975 *pp = pId->pNext;
976 sqlite3_free(pId);
977 }
978 unixLeaveMutex();
979}
980#endif /* OS_VXWORKS */
981/*************** End of Unique File ID Utility Used By VxWorks ****************
982******************************************************************************/
983
984
985/******************************************************************************
986*************************** Posix Advisory Locking ****************************
987**
drh9b35ea62008-11-29 02:20:26 +0000988** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000989** section 6.5.2.2 lines 483 through 490 specify that when a process
990** sets or clears a lock, that operation overrides any prior locks set
991** by the same process. It does not explicitly say so, but this implies
992** that it overrides locks set by the same process using a different
993** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000994**
995** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000996** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
997**
998** Suppose ./file1 and ./file2 are really the same file (because
999** one is a hard or symbolic link to the other) then if you set
1000** an exclusive lock on fd1, then try to get an exclusive lock
1001** on fd2, it works. I would have expected the second lock to
1002** fail since there was already a lock on the file due to fd1.
1003** But not so. Since both locks came from the same process, the
1004** second overrides the first, even though they were on different
1005** file descriptors opened on different file names.
1006**
drh734c9862008-11-28 15:37:20 +00001007** This means that we cannot use POSIX locks to synchronize file access
1008** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001009** to synchronize access for threads in separate processes, but not
1010** threads within the same process.
1011**
1012** To work around the problem, SQLite has to manage file locks internally
1013** on its own. Whenever a new database is opened, we have to find the
1014** specific inode of the database file (the inode is determined by the
1015** st_dev and st_ino fields of the stat structure that fstat() fills in)
1016** and check for locks already existing on that inode. When locks are
1017** created or removed, we have to look at our own internal record of the
1018** locks to see if another thread has previously set a lock on that same
1019** inode.
1020**
drh9b35ea62008-11-29 02:20:26 +00001021** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1022** For VxWorks, we have to use the alternative unique ID system based on
1023** canonical filename and implemented in the previous division.)
1024**
danielk1977ad94b582007-08-20 06:44:22 +00001025** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001026** descriptor. It is now a structure that holds the integer file
1027** descriptor and a pointer to a structure that describes the internal
1028** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001029** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001030** point to the same locking structure. The locking structure keeps
1031** a reference count (so we will know when to delete it) and a "cnt"
1032** field that tells us its internal lock status. cnt==0 means the
1033** file is unlocked. cnt==-1 means the file has an exclusive lock.
1034** cnt>0 means there are cnt shared locks on the file.
1035**
1036** Any attempt to lock or unlock a file first checks the locking
1037** structure. The fcntl() system call is only invoked to set a
1038** POSIX lock if the internal lock structure transitions between
1039** a locked and an unlocked state.
1040**
drh734c9862008-11-28 15:37:20 +00001041** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001042**
1043** If you close a file descriptor that points to a file that has locks,
1044** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001045** released. To work around this problem, each unixInodeInfo object
1046** maintains a count of the number of pending locks on tha inode.
1047** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001048** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001049** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001050** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001051** be closed and that list is walked (and cleared) when the last lock
1052** clears.
1053**
drh9b35ea62008-11-29 02:20:26 +00001054** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001055**
drh9b35ea62008-11-29 02:20:26 +00001056** Many older versions of linux use the LinuxThreads library which is
1057** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001058** A cannot be modified or overridden by a different thread B.
1059** Only thread A can modify the lock. Locking behavior is correct
1060** if the appliation uses the newer Native Posix Thread Library (NPTL)
1061** on linux - with NPTL a lock created by thread A can override locks
1062** in thread B. But there is no way to know at compile-time which
1063** threading library is being used. So there is no way to know at
1064** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001065** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001066** current process.
drh5fdae772004-06-29 03:29:00 +00001067**
drh8af6c222010-05-14 12:43:01 +00001068** SQLite used to support LinuxThreads. But support for LinuxThreads
1069** was dropped beginning with version 3.7.0. SQLite will still work with
1070** LinuxThreads provided that (1) there is no more than one connection
1071** per database file in the same process and (2) database connections
1072** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001073*/
1074
1075/*
1076** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001077** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001078*/
1079struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001080 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001081#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001082 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001083#else
drh25ef7f52016-12-05 20:06:45 +00001084 /* We are told that some versions of Android contain a bug that
1085 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1086 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1087 ** To work around this, always allocate 64-bits for the inode number.
1088 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1089 ** but that should not be a big deal. */
1090 /* WAS: ino_t ino; */
1091 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001092#endif
1093};
1094
1095/*
drhbbd42a62004-05-22 17:41:58 +00001096** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001097** inode. Or, on LinuxThreads, there is one of these structures for
1098** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001099**
danielk1977ad94b582007-08-20 06:44:22 +00001100** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001101** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001102** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001103*/
drh8af6c222010-05-14 12:43:01 +00001104struct unixInodeInfo {
1105 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001106 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001107 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1108 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001109 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001110 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1111 int nLock; /* Number of outstanding file locks */
1112 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1113 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1114 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001115#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001116 unsigned long long sharedByte; /* for AFP simulated shared lock */
1117#endif
drh6c7d5c52008-11-21 20:32:33 +00001118#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001119 sem_t *pSem; /* Named POSIX semaphore */
1120 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001121#endif
drhbbd42a62004-05-22 17:41:58 +00001122};
1123
drhda0e7682008-07-30 15:27:54 +00001124/*
drh8af6c222010-05-14 12:43:01 +00001125** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001126*/
drhc68886b2017-08-18 16:09:52 +00001127static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1128static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
drh5fdae772004-06-29 03:29:00 +00001129
drh5fdae772004-06-29 03:29:00 +00001130/*
dane18d4952011-02-21 11:46:24 +00001131**
drhaaeaa182015-11-24 15:12:47 +00001132** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001133** unixLogError().
1134**
1135** It is invoked after an error occurs in an OS function and errno has been
1136** set. It logs a message using sqlite3_log() containing the current value of
1137** errno and, if possible, the human-readable equivalent from strerror() or
1138** strerror_r().
1139**
1140** The first argument passed to the macro should be the error code that
1141** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1142** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001143** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001144** if any.
1145*/
drh0e9365c2011-03-02 02:08:13 +00001146#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1147static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001148 int errcode, /* SQLite error code */
1149 const char *zFunc, /* Name of OS function that failed */
1150 const char *zPath, /* File path associated with error */
1151 int iLine /* Source line number where error occurred */
1152){
1153 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001154 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001155
1156 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1157 ** the strerror() function to obtain the human-readable error message
1158 ** equivalent to errno. Otherwise, use strerror_r().
1159 */
1160#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1161 char aErr[80];
1162 memset(aErr, 0, sizeof(aErr));
1163 zErr = aErr;
1164
1165 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001166 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001167 ** returns a pointer to a buffer containing the error message. That pointer
1168 ** may point to aErr[], or it may point to some static storage somewhere.
1169 ** Otherwise, assume that the system provides the POSIX version of
1170 ** strerror_r(), which always writes an error message into aErr[].
1171 **
1172 ** If the code incorrectly assumes that it is the POSIX version that is
1173 ** available, the error message will often be an empty string. Not a
1174 ** huge problem. Incorrectly concluding that the GNU version is available
1175 ** could lead to a segfault though.
1176 */
1177#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1178 zErr =
1179# endif
drh0e9365c2011-03-02 02:08:13 +00001180 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001181
1182#elif SQLITE_THREADSAFE
1183 /* This is a threadsafe build, but strerror_r() is not available. */
1184 zErr = "";
1185#else
1186 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001187 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001188#endif
1189
drh0e9365c2011-03-02 02:08:13 +00001190 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001191 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001192 "os_unix.c:%d: (%d) %s(%s) - %s",
1193 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001194 );
1195
1196 return errcode;
1197}
1198
drh0e9365c2011-03-02 02:08:13 +00001199/*
1200** Close a file descriptor.
1201**
1202** We assume that close() almost always works, since it is only in a
1203** very sick application or on a very sick platform that it might fail.
1204** If it does fail, simply leak the file descriptor, but do log the
1205** error.
1206**
1207** Note that it is not safe to retry close() after EINTR since the
1208** file descriptor might have already been reused by another thread.
1209** So we don't even try to recover from an EINTR. Just log the error
1210** and move on.
1211*/
1212static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001213 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001214 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1215 pFile ? pFile->zPath : 0, lineno);
1216 }
1217}
dane18d4952011-02-21 11:46:24 +00001218
1219/*
drhe6d41732015-02-21 00:49:00 +00001220** Set the pFile->lastErrno. Do this in a subroutine as that provides
1221** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001222*/
1223static void storeLastErrno(unixFile *pFile, int error){
1224 pFile->lastErrno = error;
1225}
1226
1227/*
danb0ac3e32010-06-16 10:55:42 +00001228** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001229*/
drh0e9365c2011-03-02 02:08:13 +00001230static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001231 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001232 UnixUnusedFd *p;
1233 UnixUnusedFd *pNext;
1234 for(p=pInode->pUnused; p; p=pNext){
1235 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001236 robust_close(pFile, p->fd, __LINE__);
1237 sqlite3_free(p);
drhc68886b2017-08-18 16:09:52 +00001238 nUnusedFd--;
danb0ac3e32010-06-16 10:55:42 +00001239 }
drh0e9365c2011-03-02 02:08:13 +00001240 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001241}
1242
1243/*
drh8af6c222010-05-14 12:43:01 +00001244** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001245**
1246** The mutex entered using the unixEnterMutex() function must be held
1247** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001248*/
danb0ac3e32010-06-16 10:55:42 +00001249static void releaseInodeInfo(unixFile *pFile){
1250 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001251 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001252 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001253 pInode->nRef--;
1254 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001255 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001256 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001257 if( pInode->pPrev ){
1258 assert( pInode->pPrev->pNext==pInode );
1259 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001260 }else{
drh8af6c222010-05-14 12:43:01 +00001261 assert( inodeList==pInode );
1262 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001263 }
drh8af6c222010-05-14 12:43:01 +00001264 if( pInode->pNext ){
1265 assert( pInode->pNext->pPrev==pInode );
1266 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001267 }
drh8af6c222010-05-14 12:43:01 +00001268 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001269 }
drhbbd42a62004-05-22 17:41:58 +00001270 }
drhc68886b2017-08-18 16:09:52 +00001271 assert( inodeList!=0 || nUnusedFd==0 );
drhbbd42a62004-05-22 17:41:58 +00001272}
1273
1274/*
drh8af6c222010-05-14 12:43:01 +00001275** Given a file descriptor, locate the unixInodeInfo object that
1276** describes that file descriptor. Create a new one if necessary. The
1277** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001278**
dan9359c7b2009-08-21 08:29:10 +00001279** The mutex entered using the unixEnterMutex() function must be held
1280** when this function is called.
1281**
drh6c7d5c52008-11-21 20:32:33 +00001282** Return an appropriate error code.
1283*/
drh8af6c222010-05-14 12:43:01 +00001284static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001285 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001286 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001287){
1288 int rc; /* System call return code */
1289 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001290 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1291 struct stat statbuf; /* Low-level file information */
1292 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001293
dan9359c7b2009-08-21 08:29:10 +00001294 assert( unixMutexHeld() );
1295
drh6c7d5c52008-11-21 20:32:33 +00001296 /* Get low-level information about the file that we can used to
1297 ** create a unique name for the file.
1298 */
1299 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001300 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001301 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001302 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001303#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001304 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1305#endif
1306 return SQLITE_IOERR;
1307 }
1308
drheb0d74f2009-02-03 15:27:02 +00001309#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001310 /* On OS X on an msdos filesystem, the inode number is reported
1311 ** incorrectly for zero-size files. See ticket #3260. To work
1312 ** around this problem (we consider it a bug in OS X, not SQLite)
1313 ** we always increase the file size to 1 by writing a single byte
1314 ** prior to accessing the inode number. The one byte written is
1315 ** an ASCII 'S' character which also happens to be the first byte
1316 ** in the header of every SQLite database. In this way, if there
1317 ** is a race condition such that another thread has already populated
1318 ** the first page of the database, no damage is done.
1319 */
drh7ed97b92010-01-20 13:07:21 +00001320 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001321 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001322 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001323 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001324 return SQLITE_IOERR;
1325 }
drh99ab3b12011-03-02 15:09:07 +00001326 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001327 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001328 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001329 return SQLITE_IOERR;
1330 }
1331 }
drheb0d74f2009-02-03 15:27:02 +00001332#endif
drh6c7d5c52008-11-21 20:32:33 +00001333
drh8af6c222010-05-14 12:43:01 +00001334 memset(&fileId, 0, sizeof(fileId));
1335 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001336#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001337 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001338#else
drh25ef7f52016-12-05 20:06:45 +00001339 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001340#endif
drhc68886b2017-08-18 16:09:52 +00001341 assert( inodeList!=0 || nUnusedFd==0 );
drh8af6c222010-05-14 12:43:01 +00001342 pInode = inodeList;
1343 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1344 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001345 }
drh8af6c222010-05-14 12:43:01 +00001346 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001347 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001348 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001349 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001350 }
drh8af6c222010-05-14 12:43:01 +00001351 memset(pInode, 0, sizeof(*pInode));
1352 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1353 pInode->nRef = 1;
1354 pInode->pNext = inodeList;
1355 pInode->pPrev = 0;
1356 if( inodeList ) inodeList->pPrev = pInode;
1357 inodeList = pInode;
1358 }else{
1359 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001360 }
drh8af6c222010-05-14 12:43:01 +00001361 *ppInode = pInode;
1362 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001363}
drh6c7d5c52008-11-21 20:32:33 +00001364
drhb959a012013-12-07 12:29:22 +00001365/*
1366** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1367*/
1368static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001369#if OS_VXWORKS
1370 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1371#else
drhb959a012013-12-07 12:29:22 +00001372 struct stat buf;
1373 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001374 (osStat(pFile->zPath, &buf)!=0
1375 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001376#endif
drhb959a012013-12-07 12:29:22 +00001377}
1378
aswift5b1a2562008-08-22 00:22:35 +00001379
1380/*
drhfbc7e882013-04-11 01:16:15 +00001381** Check a unixFile that is a database. Verify the following:
1382**
1383** (1) There is exactly one hard link on the file
1384** (2) The file is not a symbolic link
1385** (3) The file has not been renamed or unlinked
1386**
1387** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1388*/
1389static void verifyDbFile(unixFile *pFile){
1390 struct stat buf;
1391 int rc;
drh86151e82015-12-08 14:37:16 +00001392
1393 /* These verifications occurs for the main database only */
1394 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1395
drhfbc7e882013-04-11 01:16:15 +00001396 rc = osFstat(pFile->h, &buf);
1397 if( rc!=0 ){
1398 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001399 return;
1400 }
drh6369bc32016-03-21 16:06:42 +00001401 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001402 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001403 return;
1404 }
1405 if( buf.st_nlink>1 ){
1406 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001407 return;
1408 }
drhb959a012013-12-07 12:29:22 +00001409 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001410 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001411 return;
1412 }
1413}
1414
1415
1416/*
danielk197713adf8a2004-06-03 16:08:41 +00001417** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001418** file by this or any other process. If such a lock is held, set *pResOut
1419** to a non-zero value otherwise *pResOut is set to zero. The return value
1420** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001421*/
danielk1977861f7452008-06-05 11:39:11 +00001422static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001423 int rc = SQLITE_OK;
1424 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001425 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001426
danielk1977861f7452008-06-05 11:39:11 +00001427 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1428
drh054889e2005-11-30 03:20:31 +00001429 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001430 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001431 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001432
1433 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001434 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001435 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001436 }
1437
drh2ac3ee92004-06-07 16:27:46 +00001438 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001439 */
danielk197709480a92009-02-09 05:32:32 +00001440#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001441 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001442 struct flock lock;
1443 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001444 lock.l_start = RESERVED_BYTE;
1445 lock.l_len = 1;
1446 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001447 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1448 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001449 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001450 } else if( lock.l_type!=F_UNLCK ){
1451 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001452 }
1453 }
danielk197709480a92009-02-09 05:32:32 +00001454#endif
danielk197713adf8a2004-06-03 16:08:41 +00001455
drh6c7d5c52008-11-21 20:32:33 +00001456 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001457 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001458
aswift5b1a2562008-08-22 00:22:35 +00001459 *pResOut = reserved;
1460 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001461}
1462
1463/*
drha7e61d82011-03-12 17:02:57 +00001464** Attempt to set a system-lock on the file pFile. The lock is
1465** described by pLock.
1466**
drh77197112011-03-15 19:08:48 +00001467** If the pFile was opened read/write from unix-excl, then the only lock
1468** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001469** the first time any lock is attempted. All subsequent system locking
1470** operations become no-ops. Locking operations still happen internally,
1471** in order to coordinate access between separate database connections
1472** within this process, but all of that is handled in memory and the
1473** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001474**
1475** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1476** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1477** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001478**
1479** Zero is returned if the call completes successfully, or -1 if a call
1480** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001481*/
1482static int unixFileLock(unixFile *pFile, struct flock *pLock){
1483 int rc;
drh3cb93392011-03-12 18:10:44 +00001484 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001485 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001486 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001487 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001488 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001489 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001490 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001491 lock.l_whence = SEEK_SET;
1492 lock.l_start = SHARED_FIRST;
1493 lock.l_len = SHARED_SIZE;
1494 lock.l_type = F_WRLCK;
1495 rc = osFcntl(pFile->h, F_SETLK, &lock);
1496 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001497 pInode->bProcessLock = 1;
1498 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001499 }else{
1500 rc = 0;
1501 }
1502 }else{
1503 rc = osFcntl(pFile->h, F_SETLK, pLock);
1504 }
1505 return rc;
1506}
1507
1508/*
drh308c2a52010-05-14 11:30:18 +00001509** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001510** of the following:
1511**
drh2ac3ee92004-06-07 16:27:46 +00001512** (1) SHARED_LOCK
1513** (2) RESERVED_LOCK
1514** (3) PENDING_LOCK
1515** (4) EXCLUSIVE_LOCK
1516**
drhb3e04342004-06-08 00:47:47 +00001517** Sometimes when requesting one lock state, additional lock states
1518** are inserted in between. The locking might fail on one of the later
1519** transitions leaving the lock state different from what it started but
1520** still short of its goal. The following chart shows the allowed
1521** transitions and the inserted intermediate states:
1522**
1523** UNLOCKED -> SHARED
1524** SHARED -> RESERVED
1525** SHARED -> (PENDING) -> EXCLUSIVE
1526** RESERVED -> (PENDING) -> EXCLUSIVE
1527** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001528**
drha6abd042004-06-09 17:37:22 +00001529** This routine will only increase a lock. Use the sqlite3OsUnlock()
1530** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001531*/
drh308c2a52010-05-14 11:30:18 +00001532static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001533 /* The following describes the implementation of the various locks and
1534 ** lock transitions in terms of the POSIX advisory shared and exclusive
1535 ** lock primitives (called read-locks and write-locks below, to avoid
1536 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001537 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001538 ** accessing the same database file, in case that is ever required.
1539 **
1540 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1541 ** byte', each single bytes at well known offsets, and the 'shared byte
1542 ** range', a range of 510 bytes at a well known offset.
1543 **
1544 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001545 ** byte'. If this is successful, 'shared byte range' is read-locked
1546 ** and the lock on the 'pending byte' released. (Legacy note: When
1547 ** SQLite was first developed, Windows95 systems were still very common,
1548 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1549 ** single randomly selected by from the 'shared byte range' is locked.
1550 ** Windows95 is now pretty much extinct, but this work-around for the
1551 ** lack of shared-locks on Windows95 lives on, for backwards
1552 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001553 **
danielk197790ba3bd2004-06-25 08:32:25 +00001554 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1555 ** A RESERVED lock is implemented by grabbing a write-lock on the
1556 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001557 **
1558 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001559 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1560 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1561 ** obtained, but existing SHARED locks are allowed to persist. A process
1562 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1563 ** This property is used by the algorithm for rolling back a journal file
1564 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001565 **
danielk197790ba3bd2004-06-25 08:32:25 +00001566 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1567 ** implemented by obtaining a write-lock on the entire 'shared byte
1568 ** range'. Since all other locks require a read-lock on one of the bytes
1569 ** within this range, this ensures that no other locks are held on the
1570 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001571 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001572 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001573 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001574 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001575 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001576 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001577
drh054889e2005-11-30 03:20:31 +00001578 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001579 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1580 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001581 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001582 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001583
1584 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001585 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001586 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001587 */
drh308c2a52010-05-14 11:30:18 +00001588 if( pFile->eFileLock>=eFileLock ){
1589 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1590 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001591 return SQLITE_OK;
1592 }
1593
drh0c2694b2009-09-03 16:23:44 +00001594 /* Make sure the locking sequence is correct.
1595 ** (1) We never move from unlocked to anything higher than shared lock.
1596 ** (2) SQLite never explicitly requests a pendig lock.
1597 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001598 */
drh308c2a52010-05-14 11:30:18 +00001599 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1600 assert( eFileLock!=PENDING_LOCK );
1601 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001602
drh8af6c222010-05-14 12:43:01 +00001603 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001604 */
drh6c7d5c52008-11-21 20:32:33 +00001605 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001606 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001607
danielk1977ad94b582007-08-20 06:44:22 +00001608 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001609 ** handle that precludes the requested lock, return BUSY.
1610 */
drh8af6c222010-05-14 12:43:01 +00001611 if( (pFile->eFileLock!=pInode->eFileLock &&
1612 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001613 ){
1614 rc = SQLITE_BUSY;
1615 goto end_lock;
1616 }
1617
1618 /* If a SHARED lock is requested, and some thread using this PID already
1619 ** has a SHARED or RESERVED lock, then increment reference counts and
1620 ** return SQLITE_OK.
1621 */
drh308c2a52010-05-14 11:30:18 +00001622 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001623 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001624 assert( eFileLock==SHARED_LOCK );
1625 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001626 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001627 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001628 pInode->nShared++;
1629 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001630 goto end_lock;
1631 }
1632
danielk19779a1d0ab2004-06-01 14:09:28 +00001633
drh3cde3bb2004-06-12 02:17:14 +00001634 /* A PENDING lock is needed before acquiring a SHARED lock and before
1635 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1636 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001637 */
drh0c2694b2009-09-03 16:23:44 +00001638 lock.l_len = 1L;
1639 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001640 if( eFileLock==SHARED_LOCK
1641 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001642 ){
drh308c2a52010-05-14 11:30:18 +00001643 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001644 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001645 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001646 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001647 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001648 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001649 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001650 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001651 goto end_lock;
1652 }
drh3cde3bb2004-06-12 02:17:14 +00001653 }
1654
1655
1656 /* If control gets to this point, then actually go ahead and make
1657 ** operating system calls for the specified lock.
1658 */
drh308c2a52010-05-14 11:30:18 +00001659 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001660 assert( pInode->nShared==0 );
1661 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001662 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001663
drh2ac3ee92004-06-07 16:27:46 +00001664 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001665 lock.l_start = SHARED_FIRST;
1666 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001667 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001668 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001669 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001670 }
dan661d71a2011-03-30 19:08:03 +00001671
drh2ac3ee92004-06-07 16:27:46 +00001672 /* Drop the temporary PENDING lock */
1673 lock.l_start = PENDING_BYTE;
1674 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001675 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001676 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1677 /* This could happen with a network mount */
1678 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001679 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001680 }
dan661d71a2011-03-30 19:08:03 +00001681
1682 if( rc ){
1683 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001684 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001685 }
dan661d71a2011-03-30 19:08:03 +00001686 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001687 }else{
drh308c2a52010-05-14 11:30:18 +00001688 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001689 pInode->nLock++;
1690 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001691 }
drh8af6c222010-05-14 12:43:01 +00001692 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001693 /* We are trying for an exclusive lock but another thread in this
1694 ** same process is still holding a shared lock. */
1695 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001696 }else{
drh3cde3bb2004-06-12 02:17:14 +00001697 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001698 ** assumed that there is a SHARED or greater lock on the file
1699 ** already.
1700 */
drh308c2a52010-05-14 11:30:18 +00001701 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001702 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001703
1704 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1705 if( eFileLock==RESERVED_LOCK ){
1706 lock.l_start = RESERVED_BYTE;
1707 lock.l_len = 1L;
1708 }else{
1709 lock.l_start = SHARED_FIRST;
1710 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001711 }
dan661d71a2011-03-30 19:08:03 +00001712
1713 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001714 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001715 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001716 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001717 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001718 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001719 }
drhbbd42a62004-05-22 17:41:58 +00001720 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001721
drh8f941bc2009-01-14 23:03:40 +00001722
drhd3d8c042012-05-29 17:02:40 +00001723#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001724 /* Set up the transaction-counter change checking flags when
1725 ** transitioning from a SHARED to a RESERVED lock. The change
1726 ** from SHARED to RESERVED marks the beginning of a normal
1727 ** write operation (not a hot journal rollback).
1728 */
1729 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001730 && pFile->eFileLock<=SHARED_LOCK
1731 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001732 ){
1733 pFile->transCntrChng = 0;
1734 pFile->dbUpdate = 0;
1735 pFile->inNormalWrite = 1;
1736 }
1737#endif
1738
1739
danielk1977ecb2a962004-06-02 06:30:16 +00001740 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001741 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001742 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001743 }else if( eFileLock==EXCLUSIVE_LOCK ){
1744 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001745 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001746 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001747
1748end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001749 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001750 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1751 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001752 return rc;
1753}
1754
1755/*
dan08da86a2009-08-21 17:18:03 +00001756** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001757** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001758*/
1759static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001760 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001761 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drh8af6c222010-05-14 12:43:01 +00001762 p->pNext = pInode->pUnused;
1763 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001764 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001765 pFile->pPreallocatedUnused = 0;
1766 nUnusedFd++;
dan08da86a2009-08-21 17:18:03 +00001767}
1768
1769/*
drh308c2a52010-05-14 11:30:18 +00001770** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001771** must be either NO_LOCK or SHARED_LOCK.
1772**
1773** If the locking level of the file descriptor is already at or below
1774** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001775**
1776** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1777** the byte range is divided into 2 parts and the first part is unlocked then
1778** set to a read lock, then the other part is simply unlocked. This works
1779** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1780** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001781*/
drha7e61d82011-03-12 17:02:57 +00001782static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001783 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001784 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001785 struct flock lock;
1786 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001787
drh054889e2005-11-30 03:20:31 +00001788 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001789 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001790 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001791 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001792
drh308c2a52010-05-14 11:30:18 +00001793 assert( eFileLock<=SHARED_LOCK );
1794 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001795 return SQLITE_OK;
1796 }
drh6c7d5c52008-11-21 20:32:33 +00001797 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001798 pInode = pFile->pInode;
1799 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001800 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001801 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001802
drhd3d8c042012-05-29 17:02:40 +00001803#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001804 /* When reducing a lock such that other processes can start
1805 ** reading the database file again, make sure that the
1806 ** transaction counter was updated if any part of the database
1807 ** file changed. If the transaction counter is not updated,
1808 ** other connections to the same file might not realize that
1809 ** the file has changed and hence might not know to flush their
1810 ** cache. The use of a stale cache can lead to database corruption.
1811 */
drh8f941bc2009-01-14 23:03:40 +00001812 pFile->inNormalWrite = 0;
1813#endif
1814
drh7ed97b92010-01-20 13:07:21 +00001815 /* downgrading to a shared lock on NFS involves clearing the write lock
1816 ** before establishing the readlock - to avoid a race condition we downgrade
1817 ** the lock in 2 blocks, so that part of the range will be covered by a
1818 ** write lock until the rest is covered by a read lock:
1819 ** 1: [WWWWW]
1820 ** 2: [....W]
1821 ** 3: [RRRRW]
1822 ** 4: [RRRR.]
1823 */
drh308c2a52010-05-14 11:30:18 +00001824 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001825#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001826 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001827 assert( handleNFSUnlock==0 );
1828#endif
1829#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001830 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001831 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001832 off_t divSize = SHARED_SIZE - 1;
1833
1834 lock.l_type = F_UNLCK;
1835 lock.l_whence = SEEK_SET;
1836 lock.l_start = SHARED_FIRST;
1837 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001838 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001839 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001840 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001841 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001842 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001843 }
drh7ed97b92010-01-20 13:07:21 +00001844 lock.l_type = F_RDLCK;
1845 lock.l_whence = SEEK_SET;
1846 lock.l_start = SHARED_FIRST;
1847 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001848 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001849 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001850 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1851 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001852 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001853 }
1854 goto end_unlock;
1855 }
1856 lock.l_type = F_UNLCK;
1857 lock.l_whence = SEEK_SET;
1858 lock.l_start = SHARED_FIRST+divSize;
1859 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001860 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001861 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001862 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001863 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001864 goto end_unlock;
1865 }
drh30f776f2011-02-25 03:25:07 +00001866 }else
1867#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1868 {
drh7ed97b92010-01-20 13:07:21 +00001869 lock.l_type = F_RDLCK;
1870 lock.l_whence = SEEK_SET;
1871 lock.l_start = SHARED_FIRST;
1872 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001873 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001874 /* In theory, the call to unixFileLock() cannot fail because another
1875 ** process is holding an incompatible lock. If it does, this
1876 ** indicates that the other process is not following the locking
1877 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1878 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1879 ** an assert to fail). */
1880 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001881 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001882 goto end_unlock;
1883 }
drh9c105bb2004-10-02 20:38:28 +00001884 }
1885 }
drhbbd42a62004-05-22 17:41:58 +00001886 lock.l_type = F_UNLCK;
1887 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001888 lock.l_start = PENDING_BYTE;
1889 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001890 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001891 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001892 }else{
danea83bc62011-04-01 11:56:32 +00001893 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001894 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001895 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001896 }
drhbbd42a62004-05-22 17:41:58 +00001897 }
drh308c2a52010-05-14 11:30:18 +00001898 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001899 /* Decrement the shared lock counter. Release the lock using an
1900 ** OS call only when all threads in this same process have released
1901 ** the lock.
1902 */
drh8af6c222010-05-14 12:43:01 +00001903 pInode->nShared--;
1904 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001905 lock.l_type = F_UNLCK;
1906 lock.l_whence = SEEK_SET;
1907 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001908 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001909 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001910 }else{
danea83bc62011-04-01 11:56:32 +00001911 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001912 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001913 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001914 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001915 }
drha6abd042004-06-09 17:37:22 +00001916 }
1917
drhbbd42a62004-05-22 17:41:58 +00001918 /* Decrement the count of locks against this same file. When the
1919 ** count reaches zero, close any other file descriptors whose close
1920 ** was deferred because of outstanding locks.
1921 */
drh8af6c222010-05-14 12:43:01 +00001922 pInode->nLock--;
1923 assert( pInode->nLock>=0 );
1924 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001925 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001926 }
1927 }
drhf2f105d2012-08-20 15:53:54 +00001928
aswift5b1a2562008-08-22 00:22:35 +00001929end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001930 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001931 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001932 return rc;
drhbbd42a62004-05-22 17:41:58 +00001933}
1934
1935/*
drh308c2a52010-05-14 11:30:18 +00001936** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001937** must be either NO_LOCK or SHARED_LOCK.
1938**
1939** If the locking level of the file descriptor is already at or below
1940** the requested locking level, this routine is a no-op.
1941*/
drh308c2a52010-05-14 11:30:18 +00001942static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001943#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001944 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001945#endif
drha7e61d82011-03-12 17:02:57 +00001946 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001947}
1948
mistachkine98844f2013-08-24 00:59:24 +00001949#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001950static int unixMapfile(unixFile *pFd, i64 nByte);
1951static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001952#endif
danf23da962013-03-23 21:00:41 +00001953
drh7ed97b92010-01-20 13:07:21 +00001954/*
danielk1977e339d652008-06-28 11:23:00 +00001955** This function performs the parts of the "close file" operation
1956** common to all locking schemes. It closes the directory and file
1957** handles, if they are valid, and sets all fields of the unixFile
1958** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001959**
1960** It is *not* necessary to hold the mutex when this routine is called,
1961** even on VxWorks. A mutex will be acquired on VxWorks by the
1962** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001963*/
1964static int closeUnixFile(sqlite3_file *id){
1965 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001966#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001967 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001968#endif
dan661d71a2011-03-30 19:08:03 +00001969 if( pFile->h>=0 ){
1970 robust_close(pFile, pFile->h, __LINE__);
1971 pFile->h = -1;
1972 }
1973#if OS_VXWORKS
1974 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001975 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001976 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001977 }
1978 vxworksReleaseFileId(pFile->pId);
1979 pFile->pId = 0;
1980 }
1981#endif
drh0bdbc902014-06-16 18:35:06 +00001982#ifdef SQLITE_UNLINK_AFTER_CLOSE
1983 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1984 osUnlink(pFile->zPath);
1985 sqlite3_free(*(char**)&pFile->zPath);
1986 pFile->zPath = 0;
1987 }
1988#endif
dan661d71a2011-03-30 19:08:03 +00001989 OSTRACE(("CLOSE %-3d\n", pFile->h));
1990 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00001991 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00001992 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001993 return SQLITE_OK;
1994}
1995
1996/*
danielk1977e3026632004-06-22 11:29:02 +00001997** Close a file.
1998*/
danielk197762079062007-08-15 17:08:46 +00001999static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002000 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002001 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00002002 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002003 unixUnlock(id, NO_LOCK);
2004 unixEnterMutex();
2005
2006 /* unixFile.pInode is always valid here. Otherwise, a different close
2007 ** routine (e.g. nolockClose()) would be called instead.
2008 */
2009 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2010 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
2011 /* If there are outstanding locks, do not actually close the file just
2012 ** yet because that would clear those locks. Instead, add the file
2013 ** descriptor to pInode->pUnused list. It will be automatically closed
2014 ** when the last lock is cleared.
2015 */
2016 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002017 }
dan661d71a2011-03-30 19:08:03 +00002018 releaseInodeInfo(pFile);
2019 rc = closeUnixFile(id);
2020 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002021 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002022}
2023
drh734c9862008-11-28 15:37:20 +00002024/************** End of the posix advisory lock implementation *****************
2025******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002026
drh734c9862008-11-28 15:37:20 +00002027/******************************************************************************
2028****************************** No-op Locking **********************************
2029**
2030** Of the various locking implementations available, this is by far the
2031** simplest: locking is ignored. No attempt is made to lock the database
2032** file for reading or writing.
2033**
2034** This locking mode is appropriate for use on read-only databases
2035** (ex: databases that are burned into CD-ROM, for example.) It can
2036** also be used if the application employs some external mechanism to
2037** prevent simultaneous access of the same database by two or more
2038** database connections. But there is a serious risk of database
2039** corruption if this locking mode is used in situations where multiple
2040** database connections are accessing the same database file at the same
2041** time and one or more of those connections are writing.
2042*/
drhbfe66312006-10-03 17:40:40 +00002043
drh734c9862008-11-28 15:37:20 +00002044static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2045 UNUSED_PARAMETER(NotUsed);
2046 *pResOut = 0;
2047 return SQLITE_OK;
2048}
drh734c9862008-11-28 15:37:20 +00002049static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2050 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2051 return SQLITE_OK;
2052}
drh734c9862008-11-28 15:37:20 +00002053static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2054 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2055 return SQLITE_OK;
2056}
2057
2058/*
drh9b35ea62008-11-29 02:20:26 +00002059** Close the file.
drh734c9862008-11-28 15:37:20 +00002060*/
2061static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002062 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002063}
2064
2065/******************* End of the no-op lock implementation *********************
2066******************************************************************************/
2067
2068/******************************************************************************
2069************************* Begin dot-file Locking ******************************
2070**
mistachkin48864df2013-03-21 21:20:32 +00002071** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002072** files (really a directory) to control access to the database. This works
2073** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002074**
2075** (1) There is zero concurrency. A single reader blocks all other
2076** connections from reading or writing the database.
2077**
2078** (2) An application crash or power loss can leave stale lock files
2079** sitting around that need to be cleared manually.
2080**
2081** Nevertheless, a dotlock is an appropriate locking mode for use if no
2082** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002083**
drh9ef6bc42011-11-04 02:24:02 +00002084** Dotfile locking works by creating a subdirectory in the same directory as
2085** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002086** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002087** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002088*/
2089
2090/*
2091** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002092** lock directory.
drh734c9862008-11-28 15:37:20 +00002093*/
2094#define DOTLOCK_SUFFIX ".lock"
2095
drh7708e972008-11-29 00:56:52 +00002096/*
2097** This routine checks if there is a RESERVED lock held on the specified
2098** file by this or any other process. If such a lock is held, set *pResOut
2099** to a non-zero value otherwise *pResOut is set to zero. The return value
2100** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2101**
2102** In dotfile locking, either a lock exists or it does not. So in this
2103** variation of CheckReservedLock(), *pResOut is set to true if any lock
2104** is held on the file and false if the file is unlocked.
2105*/
drh734c9862008-11-28 15:37:20 +00002106static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2107 int rc = SQLITE_OK;
2108 int reserved = 0;
2109 unixFile *pFile = (unixFile*)id;
2110
2111 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2112
2113 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002114 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002115 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002116 *pResOut = reserved;
2117 return rc;
2118}
2119
drh7708e972008-11-29 00:56:52 +00002120/*
drh308c2a52010-05-14 11:30:18 +00002121** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002122** of the following:
2123**
2124** (1) SHARED_LOCK
2125** (2) RESERVED_LOCK
2126** (3) PENDING_LOCK
2127** (4) EXCLUSIVE_LOCK
2128**
2129** Sometimes when requesting one lock state, additional lock states
2130** are inserted in between. The locking might fail on one of the later
2131** transitions leaving the lock state different from what it started but
2132** still short of its goal. The following chart shows the allowed
2133** transitions and the inserted intermediate states:
2134**
2135** UNLOCKED -> SHARED
2136** SHARED -> RESERVED
2137** SHARED -> (PENDING) -> EXCLUSIVE
2138** RESERVED -> (PENDING) -> EXCLUSIVE
2139** PENDING -> EXCLUSIVE
2140**
2141** This routine will only increase a lock. Use the sqlite3OsUnlock()
2142** routine to lower a locking level.
2143**
2144** With dotfile locking, we really only support state (4): EXCLUSIVE.
2145** But we track the other locking levels internally.
2146*/
drh308c2a52010-05-14 11:30:18 +00002147static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002148 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002149 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002150 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002151
drh7708e972008-11-29 00:56:52 +00002152
2153 /* If we have any lock, then the lock file already exists. All we have
2154 ** to do is adjust our internal record of the lock level.
2155 */
drh308c2a52010-05-14 11:30:18 +00002156 if( pFile->eFileLock > NO_LOCK ){
2157 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002158 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002159#ifdef HAVE_UTIME
2160 utime(zLockFile, NULL);
2161#else
drh734c9862008-11-28 15:37:20 +00002162 utimes(zLockFile, NULL);
2163#endif
drh7708e972008-11-29 00:56:52 +00002164 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002165 }
2166
2167 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002168 rc = osMkdir(zLockFile, 0777);
2169 if( rc<0 ){
2170 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002171 int tErrno = errno;
2172 if( EEXIST == tErrno ){
2173 rc = SQLITE_BUSY;
2174 } else {
2175 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002176 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002177 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002178 }
2179 }
drh7708e972008-11-29 00:56:52 +00002180 return rc;
drh734c9862008-11-28 15:37:20 +00002181 }
drh734c9862008-11-28 15:37:20 +00002182
2183 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002184 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002185 return rc;
2186}
2187
drh7708e972008-11-29 00:56:52 +00002188/*
drh308c2a52010-05-14 11:30:18 +00002189** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002190** must be either NO_LOCK or SHARED_LOCK.
2191**
2192** If the locking level of the file descriptor is already at or below
2193** the requested locking level, this routine is a no-op.
2194**
2195** When the locking level reaches NO_LOCK, delete the lock file.
2196*/
drh308c2a52010-05-14 11:30:18 +00002197static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002198 unixFile *pFile = (unixFile*)id;
2199 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002200 int rc;
drh734c9862008-11-28 15:37:20 +00002201
2202 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002203 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002204 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002205 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002206
2207 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002208 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002209 return SQLITE_OK;
2210 }
drh7708e972008-11-29 00:56:52 +00002211
2212 /* To downgrade to shared, simply update our internal notion of the
2213 ** lock state. No need to mess with the file on disk.
2214 */
drh308c2a52010-05-14 11:30:18 +00002215 if( eFileLock==SHARED_LOCK ){
2216 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002217 return SQLITE_OK;
2218 }
2219
drh7708e972008-11-29 00:56:52 +00002220 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002221 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002222 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002223 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002224 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002225 if( tErrno==ENOENT ){
2226 rc = SQLITE_OK;
2227 }else{
danea83bc62011-04-01 11:56:32 +00002228 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002229 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002230 }
2231 return rc;
2232 }
drh308c2a52010-05-14 11:30:18 +00002233 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002234 return SQLITE_OK;
2235}
2236
2237/*
drh9b35ea62008-11-29 02:20:26 +00002238** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002239*/
2240static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002241 unixFile *pFile = (unixFile*)id;
2242 assert( id!=0 );
2243 dotlockUnlock(id, NO_LOCK);
2244 sqlite3_free(pFile->lockingContext);
2245 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002246}
2247/****************** End of the dot-file lock implementation *******************
2248******************************************************************************/
2249
2250/******************************************************************************
2251************************** Begin flock Locking ********************************
2252**
2253** Use the flock() system call to do file locking.
2254**
drh6b9d6dd2008-12-03 19:34:47 +00002255** flock() locking is like dot-file locking in that the various
2256** fine-grain locking levels supported by SQLite are collapsed into
2257** a single exclusive lock. In other words, SHARED, RESERVED, and
2258** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2259** still works when you do this, but concurrency is reduced since
2260** only a single process can be reading the database at a time.
2261**
drhe89b2912015-03-03 20:42:01 +00002262** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002263*/
drhe89b2912015-03-03 20:42:01 +00002264#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002265
drh6b9d6dd2008-12-03 19:34:47 +00002266/*
drhff812312011-02-23 13:33:46 +00002267** Retry flock() calls that fail with EINTR
2268*/
2269#ifdef EINTR
2270static int robust_flock(int fd, int op){
2271 int rc;
2272 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2273 return rc;
2274}
2275#else
drh5c819272011-02-23 14:00:12 +00002276# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002277#endif
2278
2279
2280/*
drh6b9d6dd2008-12-03 19:34:47 +00002281** This routine checks if there is a RESERVED lock held on the specified
2282** file by this or any other process. If such a lock is held, set *pResOut
2283** to a non-zero value otherwise *pResOut is set to zero. The return value
2284** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2285*/
drh734c9862008-11-28 15:37:20 +00002286static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2287 int rc = SQLITE_OK;
2288 int reserved = 0;
2289 unixFile *pFile = (unixFile*)id;
2290
2291 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2292
2293 assert( pFile );
2294
2295 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002296 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002297 reserved = 1;
2298 }
2299
2300 /* Otherwise see if some other process holds it. */
2301 if( !reserved ){
2302 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002303 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002304 if( !lrc ){
2305 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002306 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002307 if ( lrc ) {
2308 int tErrno = errno;
2309 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002310 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002311 storeLastErrno(pFile, tErrno);
2312 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002313 }
2314 } else {
2315 int tErrno = errno;
2316 reserved = 1;
2317 /* someone else might have it reserved */
2318 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2319 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002320 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002321 rc = lrc;
2322 }
2323 }
2324 }
drh308c2a52010-05-14 11:30:18 +00002325 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002326
2327#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002328 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002329 rc = SQLITE_OK;
2330 reserved=1;
2331 }
2332#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2333 *pResOut = reserved;
2334 return rc;
2335}
2336
drh6b9d6dd2008-12-03 19:34:47 +00002337/*
drh308c2a52010-05-14 11:30:18 +00002338** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002339** of the following:
2340**
2341** (1) SHARED_LOCK
2342** (2) RESERVED_LOCK
2343** (3) PENDING_LOCK
2344** (4) EXCLUSIVE_LOCK
2345**
2346** Sometimes when requesting one lock state, additional lock states
2347** are inserted in between. The locking might fail on one of the later
2348** transitions leaving the lock state different from what it started but
2349** still short of its goal. The following chart shows the allowed
2350** transitions and the inserted intermediate states:
2351**
2352** UNLOCKED -> SHARED
2353** SHARED -> RESERVED
2354** SHARED -> (PENDING) -> EXCLUSIVE
2355** RESERVED -> (PENDING) -> EXCLUSIVE
2356** PENDING -> EXCLUSIVE
2357**
2358** flock() only really support EXCLUSIVE locks. We track intermediate
2359** lock states in the sqlite3_file structure, but all locks SHARED or
2360** above are really EXCLUSIVE locks and exclude all other processes from
2361** access the file.
2362**
2363** This routine will only increase a lock. Use the sqlite3OsUnlock()
2364** routine to lower a locking level.
2365*/
drh308c2a52010-05-14 11:30:18 +00002366static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002367 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002368 unixFile *pFile = (unixFile*)id;
2369
2370 assert( pFile );
2371
2372 /* if we already have a lock, it is exclusive.
2373 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002374 if (pFile->eFileLock > NO_LOCK) {
2375 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002376 return SQLITE_OK;
2377 }
2378
2379 /* grab an exclusive lock */
2380
drhff812312011-02-23 13:33:46 +00002381 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002382 int tErrno = errno;
2383 /* didn't get, must be busy */
2384 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2385 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002386 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002387 }
2388 } else {
2389 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002390 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002391 }
drh308c2a52010-05-14 11:30:18 +00002392 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2393 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002394#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002395 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002396 rc = SQLITE_BUSY;
2397 }
2398#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2399 return rc;
2400}
2401
drh6b9d6dd2008-12-03 19:34:47 +00002402
2403/*
drh308c2a52010-05-14 11:30:18 +00002404** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002405** must be either NO_LOCK or SHARED_LOCK.
2406**
2407** If the locking level of the file descriptor is already at or below
2408** the requested locking level, this routine is a no-op.
2409*/
drh308c2a52010-05-14 11:30:18 +00002410static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002411 unixFile *pFile = (unixFile*)id;
2412
2413 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002414 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002415 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002416 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002417
2418 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002419 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002420 return SQLITE_OK;
2421 }
2422
2423 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002424 if (eFileLock==SHARED_LOCK) {
2425 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002426 return SQLITE_OK;
2427 }
2428
2429 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002430 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002431#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002432 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002433#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002434 return SQLITE_IOERR_UNLOCK;
2435 }else{
drh308c2a52010-05-14 11:30:18 +00002436 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002437 return SQLITE_OK;
2438 }
2439}
2440
2441/*
2442** Close a file.
2443*/
2444static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002445 assert( id!=0 );
2446 flockUnlock(id, NO_LOCK);
2447 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002448}
2449
2450#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2451
2452/******************* End of the flock lock implementation *********************
2453******************************************************************************/
2454
2455/******************************************************************************
2456************************ Begin Named Semaphore Locking ************************
2457**
2458** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002459**
2460** Semaphore locking is like dot-lock and flock in that it really only
2461** supports EXCLUSIVE locking. Only a single process can read or write
2462** the database file at a time. This reduces potential concurrency, but
2463** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002464*/
2465#if OS_VXWORKS
2466
drh6b9d6dd2008-12-03 19:34:47 +00002467/*
2468** This routine checks if there is a RESERVED lock held on the specified
2469** file by this or any other process. If such a lock is held, set *pResOut
2470** to a non-zero value otherwise *pResOut is set to zero. The return value
2471** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2472*/
drh8cd5b252015-03-02 22:06:43 +00002473static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002474 int rc = SQLITE_OK;
2475 int reserved = 0;
2476 unixFile *pFile = (unixFile*)id;
2477
2478 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2479
2480 assert( pFile );
2481
2482 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002483 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002484 reserved = 1;
2485 }
2486
2487 /* Otherwise see if some other process holds it. */
2488 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002489 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002490
2491 if( sem_trywait(pSem)==-1 ){
2492 int tErrno = errno;
2493 if( EAGAIN != tErrno ){
2494 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002495 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002496 } else {
2497 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002498 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002499 }
2500 }else{
2501 /* we could have it if we want it */
2502 sem_post(pSem);
2503 }
2504 }
drh308c2a52010-05-14 11:30:18 +00002505 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002506
2507 *pResOut = reserved;
2508 return rc;
2509}
2510
drh6b9d6dd2008-12-03 19:34:47 +00002511/*
drh308c2a52010-05-14 11:30:18 +00002512** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002513** of the following:
2514**
2515** (1) SHARED_LOCK
2516** (2) RESERVED_LOCK
2517** (3) PENDING_LOCK
2518** (4) EXCLUSIVE_LOCK
2519**
2520** Sometimes when requesting one lock state, additional lock states
2521** are inserted in between. The locking might fail on one of the later
2522** transitions leaving the lock state different from what it started but
2523** still short of its goal. The following chart shows the allowed
2524** transitions and the inserted intermediate states:
2525**
2526** UNLOCKED -> SHARED
2527** SHARED -> RESERVED
2528** SHARED -> (PENDING) -> EXCLUSIVE
2529** RESERVED -> (PENDING) -> EXCLUSIVE
2530** PENDING -> EXCLUSIVE
2531**
2532** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2533** lock states in the sqlite3_file structure, but all locks SHARED or
2534** above are really EXCLUSIVE locks and exclude all other processes from
2535** access the file.
2536**
2537** This routine will only increase a lock. Use the sqlite3OsUnlock()
2538** routine to lower a locking level.
2539*/
drh8cd5b252015-03-02 22:06:43 +00002540static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002541 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002542 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002543 int rc = SQLITE_OK;
2544
2545 /* if we already have a lock, it is exclusive.
2546 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002547 if (pFile->eFileLock > NO_LOCK) {
2548 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002549 rc = SQLITE_OK;
2550 goto sem_end_lock;
2551 }
2552
2553 /* lock semaphore now but bail out when already locked. */
2554 if( sem_trywait(pSem)==-1 ){
2555 rc = SQLITE_BUSY;
2556 goto sem_end_lock;
2557 }
2558
2559 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002560 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002561
2562 sem_end_lock:
2563 return rc;
2564}
2565
drh6b9d6dd2008-12-03 19:34:47 +00002566/*
drh308c2a52010-05-14 11:30:18 +00002567** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002568** must be either NO_LOCK or SHARED_LOCK.
2569**
2570** If the locking level of the file descriptor is already at or below
2571** the requested locking level, this routine is a no-op.
2572*/
drh8cd5b252015-03-02 22:06:43 +00002573static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002574 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002575 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002576
2577 assert( pFile );
2578 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002579 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002580 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002581 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002582
2583 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002584 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002585 return SQLITE_OK;
2586 }
2587
2588 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002589 if (eFileLock==SHARED_LOCK) {
2590 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002591 return SQLITE_OK;
2592 }
2593
2594 /* no, really unlock. */
2595 if ( sem_post(pSem)==-1 ) {
2596 int rc, tErrno = errno;
2597 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2598 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002599 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002600 }
2601 return rc;
2602 }
drh308c2a52010-05-14 11:30:18 +00002603 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002604 return SQLITE_OK;
2605}
2606
2607/*
2608 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002609 */
drh8cd5b252015-03-02 22:06:43 +00002610static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002611 if( id ){
2612 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002613 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002614 assert( pFile );
2615 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002616 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002617 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002618 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002619 }
2620 return SQLITE_OK;
2621}
2622
2623#endif /* OS_VXWORKS */
2624/*
2625** Named semaphore locking is only available on VxWorks.
2626**
2627*************** End of the named semaphore lock implementation ****************
2628******************************************************************************/
2629
2630
2631/******************************************************************************
2632*************************** Begin AFP Locking *********************************
2633**
2634** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2635** on Apple Macintosh computers - both OS9 and OSX.
2636**
2637** Third-party implementations of AFP are available. But this code here
2638** only works on OSX.
2639*/
2640
drhd2cb50b2009-01-09 21:41:17 +00002641#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002642/*
2643** The afpLockingContext structure contains all afp lock specific state
2644*/
drhbfe66312006-10-03 17:40:40 +00002645typedef struct afpLockingContext afpLockingContext;
2646struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002647 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002648 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002649};
2650
2651struct ByteRangeLockPB2
2652{
2653 unsigned long long offset; /* offset to first byte to lock */
2654 unsigned long long length; /* nbr of bytes to lock */
2655 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2656 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2657 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2658 int fd; /* file desc to assoc this lock with */
2659};
2660
drhfd131da2007-08-07 17:13:03 +00002661#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002662
drh6b9d6dd2008-12-03 19:34:47 +00002663/*
2664** This is a utility for setting or clearing a bit-range lock on an
2665** AFP filesystem.
2666**
2667** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2668*/
2669static int afpSetLock(
2670 const char *path, /* Name of the file to be locked or unlocked */
2671 unixFile *pFile, /* Open file descriptor on path */
2672 unsigned long long offset, /* First byte to be locked */
2673 unsigned long long length, /* Number of bytes to lock */
2674 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002675){
drh6b9d6dd2008-12-03 19:34:47 +00002676 struct ByteRangeLockPB2 pb;
2677 int err;
drhbfe66312006-10-03 17:40:40 +00002678
2679 pb.unLockFlag = setLockFlag ? 0 : 1;
2680 pb.startEndFlag = 0;
2681 pb.offset = offset;
2682 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002683 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002684
drh308c2a52010-05-14 11:30:18 +00002685 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002686 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002687 offset, length));
drhbfe66312006-10-03 17:40:40 +00002688 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2689 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002690 int rc;
2691 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002692 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2693 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002694#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2695 rc = SQLITE_BUSY;
2696#else
drh734c9862008-11-28 15:37:20 +00002697 rc = sqliteErrorFromPosixError(tErrno,
2698 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002699#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002700 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002701 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002702 }
2703 return rc;
drhbfe66312006-10-03 17:40:40 +00002704 } else {
aswift5b1a2562008-08-22 00:22:35 +00002705 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002706 }
2707}
2708
drh6b9d6dd2008-12-03 19:34:47 +00002709/*
2710** This routine checks if there is a RESERVED lock held on the specified
2711** file by this or any other process. If such a lock is held, set *pResOut
2712** to a non-zero value otherwise *pResOut is set to zero. The return value
2713** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2714*/
danielk1977e339d652008-06-28 11:23:00 +00002715static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002716 int rc = SQLITE_OK;
2717 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002718 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002719 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002720
aswift5b1a2562008-08-22 00:22:35 +00002721 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2722
2723 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002724 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002725 if( context->reserved ){
2726 *pResOut = 1;
2727 return SQLITE_OK;
2728 }
drh8af6c222010-05-14 12:43:01 +00002729 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002730
2731 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002732 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002733 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002734 }
2735
2736 /* Otherwise see if some other process holds it.
2737 */
aswift5b1a2562008-08-22 00:22:35 +00002738 if( !reserved ){
2739 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002740 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002741 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002742 /* if we succeeded in taking the reserved lock, unlock it to restore
2743 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002744 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002745 } else {
2746 /* if we failed to get the lock then someone else must have it */
2747 reserved = 1;
2748 }
2749 if( IS_LOCK_ERROR(lrc) ){
2750 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002751 }
2752 }
drhbfe66312006-10-03 17:40:40 +00002753
drh7ed97b92010-01-20 13:07:21 +00002754 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002755 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002756
2757 *pResOut = reserved;
2758 return rc;
drhbfe66312006-10-03 17:40:40 +00002759}
2760
drh6b9d6dd2008-12-03 19:34:47 +00002761/*
drh308c2a52010-05-14 11:30:18 +00002762** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002763** of the following:
2764**
2765** (1) SHARED_LOCK
2766** (2) RESERVED_LOCK
2767** (3) PENDING_LOCK
2768** (4) EXCLUSIVE_LOCK
2769**
2770** Sometimes when requesting one lock state, additional lock states
2771** are inserted in between. The locking might fail on one of the later
2772** transitions leaving the lock state different from what it started but
2773** still short of its goal. The following chart shows the allowed
2774** transitions and the inserted intermediate states:
2775**
2776** UNLOCKED -> SHARED
2777** SHARED -> RESERVED
2778** SHARED -> (PENDING) -> EXCLUSIVE
2779** RESERVED -> (PENDING) -> EXCLUSIVE
2780** PENDING -> EXCLUSIVE
2781**
2782** This routine will only increase a lock. Use the sqlite3OsUnlock()
2783** routine to lower a locking level.
2784*/
drh308c2a52010-05-14 11:30:18 +00002785static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002786 int rc = SQLITE_OK;
2787 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002788 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002789 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002790
2791 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002792 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2793 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002794 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002795
drhbfe66312006-10-03 17:40:40 +00002796 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002797 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002798 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002799 */
drh308c2a52010-05-14 11:30:18 +00002800 if( pFile->eFileLock>=eFileLock ){
2801 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2802 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002803 return SQLITE_OK;
2804 }
2805
2806 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002807 ** (1) We never move from unlocked to anything higher than shared lock.
2808 ** (2) SQLite never explicitly requests a pendig lock.
2809 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002810 */
drh308c2a52010-05-14 11:30:18 +00002811 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2812 assert( eFileLock!=PENDING_LOCK );
2813 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002814
drh8af6c222010-05-14 12:43:01 +00002815 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002816 */
drh6c7d5c52008-11-21 20:32:33 +00002817 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002818 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002819
2820 /* If some thread using this PID has a lock via a different unixFile*
2821 ** handle that precludes the requested lock, return BUSY.
2822 */
drh8af6c222010-05-14 12:43:01 +00002823 if( (pFile->eFileLock!=pInode->eFileLock &&
2824 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002825 ){
2826 rc = SQLITE_BUSY;
2827 goto afp_end_lock;
2828 }
2829
2830 /* If a SHARED lock is requested, and some thread using this PID already
2831 ** has a SHARED or RESERVED lock, then increment reference counts and
2832 ** return SQLITE_OK.
2833 */
drh308c2a52010-05-14 11:30:18 +00002834 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002835 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002836 assert( eFileLock==SHARED_LOCK );
2837 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002838 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002839 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002840 pInode->nShared++;
2841 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002842 goto afp_end_lock;
2843 }
drhbfe66312006-10-03 17:40:40 +00002844
2845 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002846 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2847 ** be released.
2848 */
drh308c2a52010-05-14 11:30:18 +00002849 if( eFileLock==SHARED_LOCK
2850 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002851 ){
2852 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002853 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002854 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002855 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002856 goto afp_end_lock;
2857 }
2858 }
2859
2860 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002861 ** operating system calls for the specified lock.
2862 */
drh308c2a52010-05-14 11:30:18 +00002863 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002864 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002865 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002866
drh8af6c222010-05-14 12:43:01 +00002867 assert( pInode->nShared==0 );
2868 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002869
2870 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002871 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002872 /* note that the quality of the randomness doesn't matter that much */
2873 lk = random();
drh8af6c222010-05-14 12:43:01 +00002874 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002875 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002876 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002877 if( IS_LOCK_ERROR(lrc1) ){
2878 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002879 }
aswift5b1a2562008-08-22 00:22:35 +00002880 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002881 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002882
aswift5b1a2562008-08-22 00:22:35 +00002883 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002884 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002885 rc = lrc1;
2886 goto afp_end_lock;
2887 } else if( IS_LOCK_ERROR(lrc2) ){
2888 rc = lrc2;
2889 goto afp_end_lock;
2890 } else if( lrc1 != SQLITE_OK ) {
2891 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002892 } else {
drh308c2a52010-05-14 11:30:18 +00002893 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002894 pInode->nLock++;
2895 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002896 }
drh8af6c222010-05-14 12:43:01 +00002897 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002898 /* We are trying for an exclusive lock but another thread in this
2899 ** same process is still holding a shared lock. */
2900 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002901 }else{
2902 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2903 ** assumed that there is a SHARED or greater lock on the file
2904 ** already.
2905 */
2906 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002907 assert( 0!=pFile->eFileLock );
2908 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002909 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002910 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002911 if( !failed ){
2912 context->reserved = 1;
2913 }
drhbfe66312006-10-03 17:40:40 +00002914 }
drh308c2a52010-05-14 11:30:18 +00002915 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002916 /* Acquire an EXCLUSIVE lock */
2917
2918 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002919 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002920 */
drh6b9d6dd2008-12-03 19:34:47 +00002921 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002922 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002923 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002924 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002925 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002926 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002927 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002928 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002929 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2930 ** a critical I/O error
2931 */
drh2e233812017-08-22 15:21:54 +00002932 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00002933 SQLITE_IOERR_LOCK;
2934 goto afp_end_lock;
2935 }
2936 }else{
aswift5b1a2562008-08-22 00:22:35 +00002937 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002938 }
2939 }
aswift5b1a2562008-08-22 00:22:35 +00002940 if( failed ){
2941 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002942 }
2943 }
2944
2945 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002946 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002947 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002948 }else if( eFileLock==EXCLUSIVE_LOCK ){
2949 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002950 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002951 }
2952
2953afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002954 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002955 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2956 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002957 return rc;
2958}
2959
2960/*
drh308c2a52010-05-14 11:30:18 +00002961** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002962** must be either NO_LOCK or SHARED_LOCK.
2963**
2964** If the locking level of the file descriptor is already at or below
2965** the requested locking level, this routine is a no-op.
2966*/
drh308c2a52010-05-14 11:30:18 +00002967static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002968 int rc = SQLITE_OK;
2969 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002970 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002971 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2972 int skipShared = 0;
2973#ifdef SQLITE_TEST
2974 int h = pFile->h;
2975#endif
drhbfe66312006-10-03 17:40:40 +00002976
2977 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002978 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002979 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002980 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002981
drh308c2a52010-05-14 11:30:18 +00002982 assert( eFileLock<=SHARED_LOCK );
2983 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002984 return SQLITE_OK;
2985 }
drh6c7d5c52008-11-21 20:32:33 +00002986 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002987 pInode = pFile->pInode;
2988 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002989 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002990 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002991 SimulateIOErrorBenign(1);
2992 SimulateIOError( h=(-1) )
2993 SimulateIOErrorBenign(0);
2994
drhd3d8c042012-05-29 17:02:40 +00002995#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002996 /* When reducing a lock such that other processes can start
2997 ** reading the database file again, make sure that the
2998 ** transaction counter was updated if any part of the database
2999 ** file changed. If the transaction counter is not updated,
3000 ** other connections to the same file might not realize that
3001 ** the file has changed and hence might not know to flush their
3002 ** cache. The use of a stale cache can lead to database corruption.
3003 */
3004 assert( pFile->inNormalWrite==0
3005 || pFile->dbUpdate==0
3006 || pFile->transCntrChng==1 );
3007 pFile->inNormalWrite = 0;
3008#endif
aswiftaebf4132008-11-21 00:10:35 +00003009
drh308c2a52010-05-14 11:30:18 +00003010 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003011 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003012 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003013 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003014 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003015 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3016 } else {
3017 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003018 }
3019 }
drh308c2a52010-05-14 11:30:18 +00003020 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003021 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003022 }
drh308c2a52010-05-14 11:30:18 +00003023 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003024 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3025 if( !rc ){
3026 context->reserved = 0;
3027 }
aswiftaebf4132008-11-21 00:10:35 +00003028 }
drh8af6c222010-05-14 12:43:01 +00003029 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3030 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003031 }
aswiftaebf4132008-11-21 00:10:35 +00003032 }
drh308c2a52010-05-14 11:30:18 +00003033 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003034
drh7ed97b92010-01-20 13:07:21 +00003035 /* Decrement the shared lock counter. Release the lock using an
3036 ** OS call only when all threads in this same process have released
3037 ** the lock.
3038 */
drh8af6c222010-05-14 12:43:01 +00003039 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3040 pInode->nShared--;
3041 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003042 SimulateIOErrorBenign(1);
3043 SimulateIOError( h=(-1) )
3044 SimulateIOErrorBenign(0);
3045 if( !skipShared ){
3046 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3047 }
3048 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003049 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003050 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003051 }
3052 }
3053 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003054 pInode->nLock--;
3055 assert( pInode->nLock>=0 );
3056 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003057 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003058 }
3059 }
drhbfe66312006-10-03 17:40:40 +00003060 }
drh7ed97b92010-01-20 13:07:21 +00003061
drh6c7d5c52008-11-21 20:32:33 +00003062 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003063 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003064 return rc;
3065}
3066
3067/*
drh339eb0b2008-03-07 15:34:11 +00003068** Close a file & cleanup AFP specific locking context
3069*/
danielk1977e339d652008-06-28 11:23:00 +00003070static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003071 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003072 unixFile *pFile = (unixFile*)id;
3073 assert( id!=0 );
3074 afpUnlock(id, NO_LOCK);
3075 unixEnterMutex();
3076 if( pFile->pInode && pFile->pInode->nLock ){
3077 /* If there are outstanding locks, do not actually close the file just
3078 ** yet because that would clear those locks. Instead, add the file
3079 ** descriptor to pInode->aPending. It will be automatically closed when
3080 ** the last lock is cleared.
3081 */
3082 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003083 }
drha8de1e12015-11-30 00:05:39 +00003084 releaseInodeInfo(pFile);
3085 sqlite3_free(pFile->lockingContext);
3086 rc = closeUnixFile(id);
3087 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003088 return rc;
drhbfe66312006-10-03 17:40:40 +00003089}
3090
drhd2cb50b2009-01-09 21:41:17 +00003091#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003092/*
3093** The code above is the AFP lock implementation. The code is specific
3094** to MacOSX and does not work on other unix platforms. No alternative
3095** is available. If you don't compile for a mac, then the "unix-afp"
3096** VFS is not available.
3097**
3098********************* End of the AFP lock implementation **********************
3099******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003100
drh7ed97b92010-01-20 13:07:21 +00003101/******************************************************************************
3102*************************** Begin NFS Locking ********************************/
3103
3104#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3105/*
drh308c2a52010-05-14 11:30:18 +00003106 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003107 ** must be either NO_LOCK or SHARED_LOCK.
3108 **
3109 ** If the locking level of the file descriptor is already at or below
3110 ** the requested locking level, this routine is a no-op.
3111 */
drh308c2a52010-05-14 11:30:18 +00003112static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003113 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003114}
3115
3116#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3117/*
3118** The code above is the NFS lock implementation. The code is specific
3119** to MacOSX and does not work on other unix platforms. No alternative
3120** is available.
3121**
3122********************* End of the NFS lock implementation **********************
3123******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003124
3125/******************************************************************************
3126**************** Non-locking sqlite3_file methods *****************************
3127**
3128** The next division contains implementations for all methods of the
3129** sqlite3_file object other than the locking methods. The locking
3130** methods were defined in divisions above (one locking method per
3131** division). Those methods that are common to all locking modes
3132** are gather together into this division.
3133*/
drhbfe66312006-10-03 17:40:40 +00003134
3135/*
drh734c9862008-11-28 15:37:20 +00003136** Seek to the offset passed as the second argument, then read cnt
3137** bytes into pBuf. Return the number of bytes actually read.
3138**
3139** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3140** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3141** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003142** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003143** See tickets #2741 and #2681.
3144**
3145** To avoid stomping the errno value on a failed read the lastErrno value
3146** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003147*/
drh734c9862008-11-28 15:37:20 +00003148static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3149 int got;
drh58024642011-11-07 18:16:00 +00003150 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003151#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3152 i64 newOffset;
3153#endif
drh734c9862008-11-28 15:37:20 +00003154 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003155 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003156 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003157 do{
drh734c9862008-11-28 15:37:20 +00003158#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003159 got = osPread(id->h, pBuf, cnt, offset);
3160 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003161#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003162 got = osPread64(id->h, pBuf, cnt, offset);
3163 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003164#else
drha46cadc2016-03-04 03:02:06 +00003165 newOffset = lseek(id->h, offset, SEEK_SET);
3166 SimulateIOError( newOffset = -1 );
3167 if( newOffset<0 ){
3168 storeLastErrno((unixFile*)id, errno);
3169 return -1;
3170 }
3171 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003172#endif
drh58024642011-11-07 18:16:00 +00003173 if( got==cnt ) break;
3174 if( got<0 ){
3175 if( errno==EINTR ){ got = 1; continue; }
3176 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003177 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003178 break;
3179 }else if( got>0 ){
3180 cnt -= got;
3181 offset += got;
3182 prior += got;
3183 pBuf = (void*)(got + (char*)pBuf);
3184 }
3185 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003186 TIMER_END;
drh58024642011-11-07 18:16:00 +00003187 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3188 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3189 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003190}
3191
3192/*
drh734c9862008-11-28 15:37:20 +00003193** Read data from a file into a buffer. Return SQLITE_OK if all
3194** bytes were read successfully and SQLITE_IOERR if anything goes
3195** wrong.
drh339eb0b2008-03-07 15:34:11 +00003196*/
drh734c9862008-11-28 15:37:20 +00003197static int unixRead(
3198 sqlite3_file *id,
3199 void *pBuf,
3200 int amt,
3201 sqlite3_int64 offset
3202){
dan08da86a2009-08-21 17:18:03 +00003203 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003204 int got;
3205 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003206 assert( offset>=0 );
3207 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003208
dan08da86a2009-08-21 17:18:03 +00003209 /* If this is a database file (not a journal, master-journal or temp
3210 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003211#if 0
drhc68886b2017-08-18 16:09:52 +00003212 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003213 || offset>=PENDING_BYTE+512
3214 || offset+amt<=PENDING_BYTE
3215 );
dan7c246102010-04-12 19:00:29 +00003216#endif
drh08c6d442009-02-09 17:34:07 +00003217
drh9b4c59f2013-04-15 17:03:42 +00003218#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003219 /* Deal with as much of this read request as possible by transfering
3220 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003221 if( offset<pFile->mmapSize ){
3222 if( offset+amt <= pFile->mmapSize ){
3223 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3224 return SQLITE_OK;
3225 }else{
3226 int nCopy = pFile->mmapSize - offset;
3227 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3228 pBuf = &((u8 *)pBuf)[nCopy];
3229 amt -= nCopy;
3230 offset += nCopy;
3231 }
3232 }
drh6e0b6d52013-04-09 16:19:20 +00003233#endif
danf23da962013-03-23 21:00:41 +00003234
dan08da86a2009-08-21 17:18:03 +00003235 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003236 if( got==amt ){
3237 return SQLITE_OK;
3238 }else if( got<0 ){
3239 /* lastErrno set by seekAndRead */
3240 return SQLITE_IOERR_READ;
3241 }else{
drh4bf66fd2015-02-19 02:43:02 +00003242 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003243 /* Unread parts of the buffer must be zero-filled */
3244 memset(&((char*)pBuf)[got], 0, amt-got);
3245 return SQLITE_IOERR_SHORT_READ;
3246 }
3247}
3248
3249/*
dan47a2b4a2013-04-26 16:09:29 +00003250** Attempt to seek the file-descriptor passed as the first argument to
3251** absolute offset iOff, then attempt to write nBuf bytes of data from
3252** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3253** return the actual number of bytes written (which may be less than
3254** nBuf).
3255*/
3256static int seekAndWriteFd(
3257 int fd, /* File descriptor to write to */
3258 i64 iOff, /* File offset to begin writing at */
3259 const void *pBuf, /* Copy data from this buffer to the file */
3260 int nBuf, /* Size of buffer pBuf in bytes */
3261 int *piErrno /* OUT: Error number if error occurs */
3262){
3263 int rc = 0; /* Value returned by system call */
3264
3265 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003266 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003267 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003268 nBuf &= 0x1ffff;
3269 TIMER_START;
3270
3271#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003272 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003273#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003274 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003275#else
3276 do{
3277 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003278 SimulateIOError( iSeek = -1 );
3279 if( iSeek<0 ){
3280 rc = -1;
3281 break;
dan47a2b4a2013-04-26 16:09:29 +00003282 }
3283 rc = osWrite(fd, pBuf, nBuf);
3284 }while( rc<0 && errno==EINTR );
3285#endif
3286
3287 TIMER_END;
3288 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3289
drhe1818ec2015-12-01 16:21:35 +00003290 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003291 return rc;
3292}
3293
3294
3295/*
drh734c9862008-11-28 15:37:20 +00003296** Seek to the offset in id->offset then read cnt bytes into pBuf.
3297** Return the number of bytes actually read. Update the offset.
3298**
3299** To avoid stomping the errno value on a failed write the lastErrno value
3300** is set before returning.
3301*/
3302static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003303 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003304}
3305
3306
3307/*
3308** Write data from a buffer into a file. Return SQLITE_OK on success
3309** or some other error code on failure.
3310*/
3311static int unixWrite(
3312 sqlite3_file *id,
3313 const void *pBuf,
3314 int amt,
3315 sqlite3_int64 offset
3316){
dan08da86a2009-08-21 17:18:03 +00003317 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003318 int wrote = 0;
3319 assert( id );
3320 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003321
dan08da86a2009-08-21 17:18:03 +00003322 /* If this is a database file (not a journal, master-journal or temp
3323 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003324#if 0
drhc68886b2017-08-18 16:09:52 +00003325 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003326 || offset>=PENDING_BYTE+512
3327 || offset+amt<=PENDING_BYTE
3328 );
dan7c246102010-04-12 19:00:29 +00003329#endif
drh08c6d442009-02-09 17:34:07 +00003330
drhd3d8c042012-05-29 17:02:40 +00003331#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003332 /* If we are doing a normal write to a database file (as opposed to
3333 ** doing a hot-journal rollback or a write to some file other than a
3334 ** normal database file) then record the fact that the database
3335 ** has changed. If the transaction counter is modified, record that
3336 ** fact too.
3337 */
dan08da86a2009-08-21 17:18:03 +00003338 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003339 pFile->dbUpdate = 1; /* The database has been modified */
3340 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003341 int rc;
drh8f941bc2009-01-14 23:03:40 +00003342 char oldCntr[4];
3343 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003344 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003345 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003346 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003347 pFile->transCntrChng = 1; /* The transaction counter has changed */
3348 }
3349 }
3350 }
3351#endif
3352
danfe33e392015-11-17 20:56:06 +00003353#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003354 /* Deal with as much of this write request as possible by transfering
3355 ** data from the memory mapping using memcpy(). */
3356 if( offset<pFile->mmapSize ){
3357 if( offset+amt <= pFile->mmapSize ){
3358 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3359 return SQLITE_OK;
3360 }else{
3361 int nCopy = pFile->mmapSize - offset;
3362 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3363 pBuf = &((u8 *)pBuf)[nCopy];
3364 amt -= nCopy;
3365 offset += nCopy;
3366 }
3367 }
drh6e0b6d52013-04-09 16:19:20 +00003368#endif
drh02bf8b42015-09-01 23:51:53 +00003369
3370 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003371 amt -= wrote;
3372 offset += wrote;
3373 pBuf = &((char*)pBuf)[wrote];
3374 }
3375 SimulateIOError(( wrote=(-1), amt=1 ));
3376 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003377
drh02bf8b42015-09-01 23:51:53 +00003378 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003379 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003380 /* lastErrno set by seekAndWrite */
3381 return SQLITE_IOERR_WRITE;
3382 }else{
drh4bf66fd2015-02-19 02:43:02 +00003383 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003384 return SQLITE_FULL;
3385 }
3386 }
dan6e09d692010-07-27 18:34:15 +00003387
drh734c9862008-11-28 15:37:20 +00003388 return SQLITE_OK;
3389}
3390
3391#ifdef SQLITE_TEST
3392/*
3393** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003394** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003395*/
3396int sqlite3_sync_count = 0;
3397int sqlite3_fullsync_count = 0;
3398#endif
3399
3400/*
drh89240432009-03-25 01:06:01 +00003401** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003402** Others do no. To be safe, we will stick with the (slightly slower)
3403** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003404** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003405*/
drhf7a4a1b2015-01-10 18:02:45 +00003406#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003407# define fdatasync fsync
3408#endif
3409
3410/*
3411** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3412** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3413** only available on Mac OS X. But that could change.
3414*/
3415#ifdef F_FULLFSYNC
3416# define HAVE_FULLFSYNC 1
3417#else
3418# define HAVE_FULLFSYNC 0
3419#endif
3420
3421
3422/*
3423** The fsync() system call does not work as advertised on many
3424** unix systems. The following procedure is an attempt to make
3425** it work better.
3426**
3427** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3428** for testing when we want to run through the test suite quickly.
3429** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3430** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3431** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003432**
3433** SQLite sets the dataOnly flag if the size of the file is unchanged.
3434** The idea behind dataOnly is that it should only write the file content
3435** to disk, not the inode. We only set dataOnly if the file size is
3436** unchanged since the file size is part of the inode. However,
3437** Ted Ts'o tells us that fdatasync() will also write the inode if the
3438** file size has changed. The only real difference between fdatasync()
3439** and fsync(), Ted tells us, is that fdatasync() will not flush the
3440** inode if the mtime or owner or other inode attributes have changed.
3441** We only care about the file size, not the other file attributes, so
3442** as far as SQLite is concerned, an fdatasync() is always adequate.
3443** So, we always use fdatasync() if it is available, regardless of
3444** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003445*/
3446static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003447 int rc;
drh734c9862008-11-28 15:37:20 +00003448
3449 /* The following "ifdef/elif/else/" block has the same structure as
3450 ** the one below. It is replicated here solely to avoid cluttering
3451 ** up the real code with the UNUSED_PARAMETER() macros.
3452 */
3453#ifdef SQLITE_NO_SYNC
3454 UNUSED_PARAMETER(fd);
3455 UNUSED_PARAMETER(fullSync);
3456 UNUSED_PARAMETER(dataOnly);
3457#elif HAVE_FULLFSYNC
3458 UNUSED_PARAMETER(dataOnly);
3459#else
3460 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003461 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003462#endif
3463
3464 /* Record the number of times that we do a normal fsync() and
3465 ** FULLSYNC. This is used during testing to verify that this procedure
3466 ** gets called with the correct arguments.
3467 */
3468#ifdef SQLITE_TEST
3469 if( fullSync ) sqlite3_fullsync_count++;
3470 sqlite3_sync_count++;
3471#endif
3472
3473 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003474 ** no-op. But go ahead and call fstat() to validate the file
3475 ** descriptor as we need a method to provoke a failure during
3476 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003477 */
3478#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003479 {
3480 struct stat buf;
3481 rc = osFstat(fd, &buf);
3482 }
drh734c9862008-11-28 15:37:20 +00003483#elif HAVE_FULLFSYNC
3484 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003485 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003486 }else{
3487 rc = 1;
3488 }
3489 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003490 ** It shouldn't be possible for fullfsync to fail on the local
3491 ** file system (on OSX), so failure indicates that FULLFSYNC
3492 ** isn't supported for this file system. So, attempt an fsync
3493 ** and (for now) ignore the overhead of a superfluous fcntl call.
3494 ** It'd be better to detect fullfsync support once and avoid
3495 ** the fcntl call every time sync is called.
3496 */
drh734c9862008-11-28 15:37:20 +00003497 if( rc ) rc = fsync(fd);
3498
drh7ed97b92010-01-20 13:07:21 +00003499#elif defined(__APPLE__)
3500 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3501 ** so currently we default to the macro that redefines fdatasync to fsync
3502 */
3503 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003504#else
drh0b647ff2009-03-21 14:41:04 +00003505 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003506#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003507 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003508 rc = fsync(fd);
3509 }
drh0b647ff2009-03-21 14:41:04 +00003510#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003511#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3512
3513 if( OS_VXWORKS && rc!= -1 ){
3514 rc = 0;
3515 }
chw97185482008-11-17 08:05:31 +00003516 return rc;
drhbfe66312006-10-03 17:40:40 +00003517}
3518
drh734c9862008-11-28 15:37:20 +00003519/*
drh0059eae2011-08-08 23:48:40 +00003520** Open a file descriptor to the directory containing file zFilename.
3521** If successful, *pFd is set to the opened file descriptor and
3522** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3523** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3524** value.
3525**
drh90315a22011-08-10 01:52:12 +00003526** The directory file descriptor is used for only one thing - to
3527** fsync() a directory to make sure file creation and deletion events
3528** are flushed to disk. Such fsyncs are not needed on newer
3529** journaling filesystems, but are required on older filesystems.
3530**
3531** This routine can be overridden using the xSetSysCall interface.
3532** The ability to override this routine was added in support of the
3533** chromium sandbox. Opening a directory is a security risk (we are
3534** told) so making it overrideable allows the chromium sandbox to
3535** replace this routine with a harmless no-op. To make this routine
3536** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3537** *pFd set to a negative number.
3538**
drh0059eae2011-08-08 23:48:40 +00003539** If SQLITE_OK is returned, the caller is responsible for closing
3540** the file descriptor *pFd using close().
3541*/
3542static int openDirectory(const char *zFilename, int *pFd){
3543 int ii;
3544 int fd = -1;
3545 char zDirname[MAX_PATHNAME+1];
3546
3547 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003548 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3549 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003550 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003551 }else{
3552 if( zDirname[0]!='/' ) zDirname[0] = '.';
3553 zDirname[1] = 0;
3554 }
3555 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3556 if( fd>=0 ){
3557 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003558 }
3559 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003560 if( fd>=0 ) return SQLITE_OK;
3561 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003562}
3563
3564/*
drh734c9862008-11-28 15:37:20 +00003565** Make sure all writes to a particular file are committed to disk.
3566**
3567** If dataOnly==0 then both the file itself and its metadata (file
3568** size, access time, etc) are synced. If dataOnly!=0 then only the
3569** file data is synced.
3570**
3571** Under Unix, also make sure that the directory entry for the file
3572** has been created by fsync-ing the directory that contains the file.
3573** If we do not do this and we encounter a power failure, the directory
3574** entry for the journal might not exist after we reboot. The next
3575** SQLite to access the file will not know that the journal exists (because
3576** the directory entry for the journal was never created) and the transaction
3577** will not roll back - possibly leading to database corruption.
3578*/
3579static int unixSync(sqlite3_file *id, int flags){
3580 int rc;
3581 unixFile *pFile = (unixFile*)id;
3582
3583 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3584 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3585
3586 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3587 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3588 || (flags&0x0F)==SQLITE_SYNC_FULL
3589 );
3590
3591 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3592 ** line is to test that doing so does not cause any problems.
3593 */
3594 SimulateDiskfullError( return SQLITE_FULL );
3595
3596 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003597 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003598 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3599 SimulateIOError( rc=1 );
3600 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003601 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003602 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003603 }
drh0059eae2011-08-08 23:48:40 +00003604
3605 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003606 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003607 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003608 */
3609 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3610 int dirfd;
3611 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003612 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003613 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003614 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003615 full_fsync(dirfd, 0, 0);
3616 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003617 }else{
3618 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003619 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003620 }
drh0059eae2011-08-08 23:48:40 +00003621 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003622 }
3623 return rc;
3624}
3625
3626/*
3627** Truncate an open file to a specified size
3628*/
3629static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003630 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003631 int rc;
dan6e09d692010-07-27 18:34:15 +00003632 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003633 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003634
3635 /* If the user has configured a chunk-size for this file, truncate the
3636 ** file so that it consists of an integer number of chunks (i.e. the
3637 ** actual file size after the operation may be larger than the requested
3638 ** size).
3639 */
drhb8af4b72012-04-05 20:04:39 +00003640 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003641 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3642 }
3643
dan2ee53412014-09-06 16:49:40 +00003644 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003645 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003646 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003647 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003648 }else{
drhd3d8c042012-05-29 17:02:40 +00003649#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003650 /* If we are doing a normal write to a database file (as opposed to
3651 ** doing a hot-journal rollback or a write to some file other than a
3652 ** normal database file) and we truncate the file to zero length,
3653 ** that effectively updates the change counter. This might happen
3654 ** when restoring a database using the backup API from a zero-length
3655 ** source.
3656 */
dan6e09d692010-07-27 18:34:15 +00003657 if( pFile->inNormalWrite && nByte==0 ){
3658 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003659 }
danf23da962013-03-23 21:00:41 +00003660#endif
danc0003312013-03-22 17:46:11 +00003661
mistachkine98844f2013-08-24 00:59:24 +00003662#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003663 /* If the file was just truncated to a size smaller than the currently
3664 ** mapped region, reduce the effective mapping size as well. SQLite will
3665 ** use read() and write() to access data beyond this point from now on.
3666 */
3667 if( nByte<pFile->mmapSize ){
3668 pFile->mmapSize = nByte;
3669 }
mistachkine98844f2013-08-24 00:59:24 +00003670#endif
drh3313b142009-11-06 04:13:18 +00003671
drh734c9862008-11-28 15:37:20 +00003672 return SQLITE_OK;
3673 }
3674}
3675
3676/*
3677** Determine the current size of a file in bytes
3678*/
3679static int unixFileSize(sqlite3_file *id, i64 *pSize){
3680 int rc;
3681 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003682 assert( id );
3683 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003684 SimulateIOError( rc=1 );
3685 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003686 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003687 return SQLITE_IOERR_FSTAT;
3688 }
3689 *pSize = buf.st_size;
3690
drh8af6c222010-05-14 12:43:01 +00003691 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003692 ** writes a single byte into that file in order to work around a bug
3693 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3694 ** layers, we need to report this file size as zero even though it is
3695 ** really 1. Ticket #3260.
3696 */
3697 if( *pSize==1 ) *pSize = 0;
3698
3699
3700 return SQLITE_OK;
3701}
3702
drhd2cb50b2009-01-09 21:41:17 +00003703#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003704/*
3705** Handler for proxy-locking file-control verbs. Defined below in the
3706** proxying locking division.
3707*/
3708static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003709#endif
drh715ff302008-12-03 22:32:44 +00003710
dan502019c2010-07-28 14:26:17 +00003711/*
3712** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003713** file-control operation. Enlarge the database to nBytes in size
3714** (rounded up to the next chunk-size). If the database is already
3715** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003716*/
3717static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003718 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003719 i64 nSize; /* Required file size */
3720 struct stat buf; /* Used to hold return values of fstat() */
3721
drh4bf66fd2015-02-19 02:43:02 +00003722 if( osFstat(pFile->h, &buf) ){
3723 return SQLITE_IOERR_FSTAT;
3724 }
dan502019c2010-07-28 14:26:17 +00003725
3726 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3727 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003728
dan502019c2010-07-28 14:26:17 +00003729#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003730 /* The code below is handling the return value of osFallocate()
3731 ** correctly. posix_fallocate() is defined to "returns zero on success,
3732 ** or an error number on failure". See the manpage for details. */
3733 int err;
drhff812312011-02-23 13:33:46 +00003734 do{
dan661d71a2011-03-30 19:08:03 +00003735 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3736 }while( err==EINTR );
3737 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003738#else
dan592bf7f2014-12-30 19:58:31 +00003739 /* If the OS does not have posix_fallocate(), fake it. Write a
3740 ** single byte to the last byte in each block that falls entirely
3741 ** within the extended region. Then, if required, a single byte
3742 ** at offset (nSize-1), to set the size of the file correctly.
3743 ** This is a similar technique to that used by glibc on systems
3744 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003745 */
3746 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003747 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003748 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003749
drh053378d2015-12-01 22:09:42 +00003750 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003751 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003752 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003753 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3754 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003755 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003756 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003757 }
dan502019c2010-07-28 14:26:17 +00003758#endif
3759 }
3760 }
3761
mistachkine98844f2013-08-24 00:59:24 +00003762#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003763 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003764 int rc;
3765 if( pFile->szChunk<=0 ){
3766 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003767 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003768 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3769 }
3770 }
3771
3772 rc = unixMapfile(pFile, nByte);
3773 return rc;
3774 }
mistachkine98844f2013-08-24 00:59:24 +00003775#endif
danf23da962013-03-23 21:00:41 +00003776
dan502019c2010-07-28 14:26:17 +00003777 return SQLITE_OK;
3778}
danielk1977ad94b582007-08-20 06:44:22 +00003779
danielk1977e3026632004-06-22 11:29:02 +00003780/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003781** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003782** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3783**
3784** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3785*/
3786static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3787 if( *pArg<0 ){
3788 *pArg = (pFile->ctrlFlags & mask)!=0;
3789 }else if( (*pArg)==0 ){
3790 pFile->ctrlFlags &= ~mask;
3791 }else{
3792 pFile->ctrlFlags |= mask;
3793 }
3794}
3795
drh696b33e2012-12-06 19:01:42 +00003796/* Forward declaration */
3797static int unixGetTempname(int nBuf, char *zBuf);
3798
drhf12b3f62011-12-21 14:42:29 +00003799/*
drh9e33c2c2007-08-31 18:34:59 +00003800** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003801*/
drhcc6bb3e2007-08-31 16:11:35 +00003802static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003803 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003804 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003805#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003806 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3807 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003808 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003809 }
3810 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3811 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003812 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003813 }
3814 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3815 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003816 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003817 }
drhd76dba72017-07-22 16:00:34 +00003818#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003819
drh9e33c2c2007-08-31 18:34:59 +00003820 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003821 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003822 return SQLITE_OK;
3823 }
drh4bf66fd2015-02-19 02:43:02 +00003824 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003825 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003826 return SQLITE_OK;
3827 }
dan6e09d692010-07-27 18:34:15 +00003828 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003829 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003830 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003831 }
drh9ff27ec2010-05-19 19:26:05 +00003832 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003833 int rc;
3834 SimulateIOErrorBenign(1);
3835 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3836 SimulateIOErrorBenign(0);
3837 return rc;
drhf0b190d2011-07-26 16:03:07 +00003838 }
3839 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003840 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3841 return SQLITE_OK;
3842 }
drhcb15f352011-12-23 01:04:17 +00003843 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3844 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003845 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003846 }
drhde60fc22011-12-14 17:53:36 +00003847 case SQLITE_FCNTL_VFSNAME: {
3848 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3849 return SQLITE_OK;
3850 }
drh696b33e2012-12-06 19:01:42 +00003851 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003852 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003853 if( zTFile ){
3854 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3855 *(char**)pArg = zTFile;
3856 }
3857 return SQLITE_OK;
3858 }
drhb959a012013-12-07 12:29:22 +00003859 case SQLITE_FCNTL_HAS_MOVED: {
3860 *(int*)pArg = fileHasMoved(pFile);
3861 return SQLITE_OK;
3862 }
mistachkine98844f2013-08-24 00:59:24 +00003863#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003864 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003865 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003866 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003867 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3868 newLimit = sqlite3GlobalConfig.mxMmap;
3869 }
dan43c1e622017-08-07 18:13:28 +00003870
3871 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00003872 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3873 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00003874 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00003875 newLimit = (newLimit & 0x7FFFFFFF);
3876 }
3877
drh9b4c59f2013-04-15 17:03:42 +00003878 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003879 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003880 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003881 if( pFile->mmapSize>0 ){
3882 unixUnmapfile(pFile);
3883 rc = unixMapfile(pFile, -1);
3884 }
danbcb8a862013-04-08 15:30:41 +00003885 }
drh34e258c2013-05-23 01:40:53 +00003886 return rc;
danb2d3de32013-03-14 18:34:37 +00003887 }
mistachkine98844f2013-08-24 00:59:24 +00003888#endif
drhd3d8c042012-05-29 17:02:40 +00003889#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003890 /* The pager calls this method to signal that it has done
3891 ** a rollback and that the database is therefore unchanged and
3892 ** it hence it is OK for the transaction change counter to be
3893 ** unchanged.
3894 */
3895 case SQLITE_FCNTL_DB_UNCHANGED: {
3896 ((unixFile*)id)->dbUpdate = 0;
3897 return SQLITE_OK;
3898 }
3899#endif
drhd2cb50b2009-01-09 21:41:17 +00003900#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003901 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3902 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003903 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003904 }
drhd2cb50b2009-01-09 21:41:17 +00003905#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003906 }
drh0b52b7d2011-01-26 19:46:22 +00003907 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003908}
3909
3910/*
danefe16972017-07-20 19:49:14 +00003911** If pFd->sectorSize is non-zero when this function is called, it is a
3912** no-op. Otherwise, the values of pFd->sectorSize and
3913** pFd->deviceCharacteristics are set according to the file-system
3914** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00003915**
danefe16972017-07-20 19:49:14 +00003916** There are two versions of this function. One for QNX and one for all
3917** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00003918*/
danefe16972017-07-20 19:49:14 +00003919#ifndef __QNXNTO__
3920static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00003921 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00003922 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00003923#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003924 int res;
dan9d709542017-07-21 21:06:24 +00003925 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00003926
danefe16972017-07-20 19:49:14 +00003927 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00003928 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
3929 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00003930 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00003931 }
drhd76dba72017-07-22 16:00:34 +00003932#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003933
3934 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3935 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3936 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3937 }
3938
3939 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3940 }
3941}
3942#else
drh537dddf2012-10-26 13:46:24 +00003943#include <sys/dcmd_blk.h>
3944#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00003945static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00003946 if( pFile->sectorSize == 0 ){
3947 struct statvfs fsInfo;
3948
3949 /* Set defaults for non-supported filesystems */
3950 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3951 pFile->deviceCharacteristics = 0;
3952 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3953 return pFile->sectorSize;
3954 }
3955
3956 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3957 pFile->sectorSize = fsInfo.f_bsize;
3958 pFile->deviceCharacteristics =
3959 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3960 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3961 ** the write succeeds */
3962 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3963 ** so it is ordered */
3964 0;
3965 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3966 pFile->sectorSize = fsInfo.f_bsize;
3967 pFile->deviceCharacteristics =
3968 /* etfs cluster size writes are atomic */
3969 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3970 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3971 ** the write succeeds */
3972 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3973 ** so it is ordered */
3974 0;
3975 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3976 pFile->sectorSize = fsInfo.f_bsize;
3977 pFile->deviceCharacteristics =
3978 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3979 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3980 ** the write succeeds */
3981 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3982 ** so it is ordered */
3983 0;
3984 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3985 pFile->sectorSize = fsInfo.f_bsize;
3986 pFile->deviceCharacteristics =
3987 /* full bitset of atomics from max sector size and smaller */
3988 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3989 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3990 ** so it is ordered */
3991 0;
3992 }else if( strstr(fsInfo.f_basetype, "dos") ){
3993 pFile->sectorSize = fsInfo.f_bsize;
3994 pFile->deviceCharacteristics =
3995 /* full bitset of atomics from max sector size and smaller */
3996 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3997 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3998 ** so it is ordered */
3999 0;
4000 }else{
4001 pFile->deviceCharacteristics =
4002 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4003 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4004 ** the write succeeds */
4005 0;
4006 }
4007 }
4008 /* Last chance verification. If the sector size isn't a multiple of 512
4009 ** then it isn't valid.*/
4010 if( pFile->sectorSize % 512 != 0 ){
4011 pFile->deviceCharacteristics = 0;
4012 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4013 }
drh537dddf2012-10-26 13:46:24 +00004014}
danefe16972017-07-20 19:49:14 +00004015#endif
4016
4017/*
4018** Return the sector size in bytes of the underlying block device for
4019** the specified file. This is almost always 512 bytes, but may be
4020** larger for some devices.
4021**
4022** SQLite code assumes this function cannot fail. It also assumes that
4023** if two files are created in the same file-system directory (i.e.
4024** a database and its journal file) that the sector size will be the
4025** same for both.
4026*/
4027static int unixSectorSize(sqlite3_file *id){
4028 unixFile *pFd = (unixFile*)id;
4029 setDeviceCharacteristics(pFd);
4030 return pFd->sectorSize;
4031}
danielk1977a3d4c882007-03-23 10:08:38 +00004032
danielk197790949c22007-08-17 16:50:38 +00004033/*
drhf12b3f62011-12-21 14:42:29 +00004034** Return the device characteristics for the file.
4035**
drhcb15f352011-12-23 01:04:17 +00004036** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004037** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004038** file system does not always provide powersafe overwrites. (In other
4039** words, after a power-loss event, parts of the file that were never
4040** written might end up being altered.) However, non-PSOW behavior is very,
4041** very rare. And asserting PSOW makes a large reduction in the amount
4042** of required I/O for journaling, since a lot of padding is eliminated.
4043** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4044** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004045*/
drhf12b3f62011-12-21 14:42:29 +00004046static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004047 unixFile *pFd = (unixFile*)id;
4048 setDeviceCharacteristics(pFd);
4049 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004050}
4051
dan702eec12014-06-23 10:04:58 +00004052#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004053
dan702eec12014-06-23 10:04:58 +00004054/*
4055** Return the system page size.
4056**
4057** This function should not be called directly by other code in this file.
4058** Instead, it should be called via macro osGetpagesize().
4059*/
4060static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004061#if OS_VXWORKS
4062 return 1024;
4063#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004064 return getpagesize();
4065#else
4066 return (int)sysconf(_SC_PAGESIZE);
4067#endif
4068}
4069
4070#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4071
4072#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004073
4074/*
drhd91c68f2010-05-14 14:52:25 +00004075** Object used to represent an shared memory buffer.
4076**
4077** When multiple threads all reference the same wal-index, each thread
4078** has its own unixShm object, but they all point to a single instance
4079** of this unixShmNode object. In other words, each wal-index is opened
4080** only once per process.
4081**
4082** Each unixShmNode object is connected to a single unixInodeInfo object.
4083** We could coalesce this object into unixInodeInfo, but that would mean
4084** every open file that does not use shared memory (in other words, most
4085** open files) would have to carry around this extra information. So
4086** the unixInodeInfo object contains a pointer to this unixShmNode object
4087** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004088**
4089** unixMutexHeld() must be true when creating or destroying
4090** this object or while reading or writing the following fields:
4091**
4092** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004093**
4094** The following fields are read-only after the object is created:
4095**
4096** fid
4097** zFilename
4098**
drhd91c68f2010-05-14 14:52:25 +00004099** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004100** unixMutexHeld() is true when reading or writing any other field
4101** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004102*/
drhd91c68f2010-05-14 14:52:25 +00004103struct unixShmNode {
4104 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004105 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004106 char *zFilename; /* Name of the mmapped file */
4107 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004108 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004109 u16 nRegion; /* Size of array apRegion */
4110 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004111 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004112 int nRef; /* Number of unixShm objects pointing to this */
4113 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004114#ifdef SQLITE_DEBUG
4115 u8 exclMask; /* Mask of exclusive locks held */
4116 u8 sharedMask; /* Mask of shared locks held */
4117 u8 nextShmId; /* Next available unixShm.id value */
4118#endif
4119};
4120
4121/*
drhd9e5c4f2010-05-12 18:01:39 +00004122** Structure used internally by this VFS to record the state of an
4123** open shared memory connection.
4124**
drhd91c68f2010-05-14 14:52:25 +00004125** The following fields are initialized when this object is created and
4126** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004127**
drhd91c68f2010-05-14 14:52:25 +00004128** unixShm.pFile
4129** unixShm.id
4130**
4131** All other fields are read/write. The unixShm.pFile->mutex must be held
4132** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004133*/
4134struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004135 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4136 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004137 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004138 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004139 u16 sharedMask; /* Mask of shared locks held */
4140 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004141};
4142
4143/*
drhd9e5c4f2010-05-12 18:01:39 +00004144** Constants used for locking
4145*/
drhbd9676c2010-06-23 17:58:38 +00004146#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004147#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004148
drhd9e5c4f2010-05-12 18:01:39 +00004149/*
drh73b64e42010-05-30 19:55:15 +00004150** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004151**
4152** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4153** otherwise.
4154*/
4155static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004156 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004157 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004158 int ofst, /* First byte of the locking range */
4159 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004160){
drhbbf76ee2015-03-10 20:22:35 +00004161 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4162 struct flock f; /* The posix advisory locking structure */
4163 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004164
drhd91c68f2010-05-14 14:52:25 +00004165 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004166 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004167 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004168
dan9181ae92017-10-26 17:05:22 +00004169 /* Shared locks never span more than one byte */
4170 assert( n==1 || lockType!=F_RDLCK );
4171
4172 /* Locks are within range */
4173 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4174
drh3cb93392011-03-12 18:10:44 +00004175 if( pShmNode->h>=0 ){
4176 /* Initialize the locking parameters */
4177 memset(&f, 0, sizeof(f));
4178 f.l_type = lockType;
4179 f.l_whence = SEEK_SET;
4180 f.l_start = ofst;
4181 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004182
drhdcfb9652015-12-02 00:05:26 +00004183 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004184 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4185 }
drhd9e5c4f2010-05-12 18:01:39 +00004186
4187 /* Update the global lock state and do debug tracing */
4188#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004189 { u16 mask;
4190 OSTRACE(("SHM-LOCK "));
4191 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4192 if( rc==SQLITE_OK ){
4193 if( lockType==F_UNLCK ){
4194 OSTRACE(("unlock %d ok", ofst));
4195 pShmNode->exclMask &= ~mask;
4196 pShmNode->sharedMask &= ~mask;
4197 }else if( lockType==F_RDLCK ){
4198 OSTRACE(("read-lock %d ok", ofst));
4199 pShmNode->exclMask &= ~mask;
4200 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004201 }else{
dan9181ae92017-10-26 17:05:22 +00004202 assert( lockType==F_WRLCK );
4203 OSTRACE(("write-lock %d ok", ofst));
4204 pShmNode->exclMask |= mask;
4205 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004206 }
dan9181ae92017-10-26 17:05:22 +00004207 }else{
4208 if( lockType==F_UNLCK ){
4209 OSTRACE(("unlock %d failed", ofst));
4210 }else if( lockType==F_RDLCK ){
4211 OSTRACE(("read-lock failed"));
4212 }else{
4213 assert( lockType==F_WRLCK );
4214 OSTRACE(("write-lock %d failed", ofst));
4215 }
4216 }
4217 OSTRACE((" - afterwards %03x,%03x\n",
4218 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004219 }
drhd9e5c4f2010-05-12 18:01:39 +00004220#endif
4221
4222 return rc;
4223}
4224
dan781e34c2014-03-20 08:59:47 +00004225/*
dan781e34c2014-03-20 08:59:47 +00004226** Return the minimum number of 32KB shm regions that should be mapped at
4227** a time, assuming that each mapping must be an integer multiple of the
4228** current system page-size.
4229**
4230** Usually, this is 1. The exception seems to be systems that are configured
4231** to use 64KB pages - in this case each mapping must cover at least two
4232** shm regions.
4233*/
4234static int unixShmRegionPerMap(void){
4235 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004236 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004237 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4238 if( pgsz<shmsz ) return 1;
4239 return pgsz/shmsz;
4240}
drhd9e5c4f2010-05-12 18:01:39 +00004241
4242/*
drhd91c68f2010-05-14 14:52:25 +00004243** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004244**
4245** This is not a VFS shared-memory method; it is a utility function called
4246** by VFS shared-memory methods.
4247*/
drhd91c68f2010-05-14 14:52:25 +00004248static void unixShmPurge(unixFile *pFd){
4249 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004250 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004251 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004252 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004253 int i;
drhd91c68f2010-05-14 14:52:25 +00004254 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004255 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004256 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004257 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004258 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004259 }else{
4260 sqlite3_free(p->apRegion[i]);
4261 }
dan13a3cb82010-06-11 19:04:21 +00004262 }
dan18801912010-06-14 14:07:50 +00004263 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004264 if( p->h>=0 ){
4265 robust_close(pFd, p->h, __LINE__);
4266 p->h = -1;
4267 }
drhd91c68f2010-05-14 14:52:25 +00004268 p->pInode->pShmNode = 0;
4269 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004270 }
4271}
4272
4273/*
danda9fe0c2010-07-13 18:44:03 +00004274** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004275** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004276**
drh7234c6d2010-06-19 15:10:09 +00004277** The file used to implement shared-memory is in the same directory
4278** as the open database file and has the same name as the open database
4279** file with the "-shm" suffix added. For example, if the database file
4280** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004281** for shared memory will be called "/home/user1/config.db-shm".
4282**
4283** Another approach to is to use files in /dev/shm or /dev/tmp or an
4284** some other tmpfs mount. But if a file in a different directory
4285** from the database file is used, then differing access permissions
4286** or a chroot() might cause two different processes on the same
4287** database to end up using different files for shared memory -
4288** meaning that their memory would not really be shared - resulting
4289** in database corruption. Nevertheless, this tmpfs file usage
4290** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4291** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4292** option results in an incompatible build of SQLite; builds of SQLite
4293** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4294** same database file at the same time, database corruption will likely
4295** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4296** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004297**
4298** When opening a new shared-memory file, if no other instances of that
4299** file are currently open, in this process or in other processes, then
4300** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004301**
4302** If the original database file (pDbFd) is using the "unix-excl" VFS
4303** that means that an exclusive lock is held on the database file and
4304** that no other processes are able to read or write the database. In
4305** that case, we do not really need shared memory. No shared memory
4306** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004307*/
danda9fe0c2010-07-13 18:44:03 +00004308static int unixOpenSharedMemory(unixFile *pDbFd){
4309 struct unixShm *p = 0; /* The connection to be opened */
4310 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4311 int rc; /* Result code */
4312 unixInodeInfo *pInode; /* The inode of fd */
4313 char *zShmFilename; /* Name of the file used for SHM */
4314 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004315
danda9fe0c2010-07-13 18:44:03 +00004316 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004317 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004318 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004319 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004320 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004321
danda9fe0c2010-07-13 18:44:03 +00004322 /* Check to see if a unixShmNode object already exists. Reuse an existing
4323 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004324 */
4325 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004326 pInode = pDbFd->pInode;
4327 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004328 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004329 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004330#ifndef SQLITE_SHM_DIRECTORY
4331 const char *zBasePath = pDbFd->zPath;
4332#endif
danddb0ac42010-07-14 14:48:58 +00004333
4334 /* Call fstat() to figure out the permissions on the database file. If
4335 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004336 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004337 */
drhf3b1ed02015-12-02 13:11:03 +00004338 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004339 rc = SQLITE_IOERR_FSTAT;
4340 goto shm_open_err;
4341 }
4342
drha4ced192010-07-15 18:32:40 +00004343#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004344 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004345#else
drh4bf66fd2015-02-19 02:43:02 +00004346 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004347#endif
drhf3cdcdc2015-04-29 16:50:28 +00004348 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004349 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004350 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004351 goto shm_open_err;
4352 }
drh9cb5a0d2012-01-05 21:19:54 +00004353 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004354 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004355#ifdef SQLITE_SHM_DIRECTORY
4356 sqlite3_snprintf(nShmFilename, zShmFilename,
4357 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4358 (u32)sStat.st_ino, (u32)sStat.st_dev);
4359#else
drh4bf66fd2015-02-19 02:43:02 +00004360 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004361 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004362#endif
drhd91c68f2010-05-14 14:52:25 +00004363 pShmNode->h = -1;
4364 pDbFd->pInode->pShmNode = pShmNode;
4365 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004366 if( sqlite3GlobalConfig.bCoreMutex ){
4367 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4368 if( pShmNode->mutex==0 ){
4369 rc = SQLITE_NOMEM_BKPT;
4370 goto shm_open_err;
4371 }
drhd91c68f2010-05-14 14:52:25 +00004372 }
drhd9e5c4f2010-05-12 18:01:39 +00004373
drh3cb93392011-03-12 18:10:44 +00004374 if( pInode->bProcessLock==0 ){
dan176b2a92017-11-01 06:59:19 +00004375 struct flock lock;
drh3ec4a0c2011-10-11 18:18:54 +00004376 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004377 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004378 openFlags = O_RDONLY;
4379 pShmNode->isReadonly = 1;
4380 }
4381 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004382 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004383 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4384 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004385 }
drhac7c3ac2012-02-11 19:23:48 +00004386
4387 /* If this process is running as root, make sure that the SHM file
4388 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004389 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004390 */
drh6226ca22015-11-24 15:06:28 +00004391 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004392
dan176b2a92017-11-01 06:59:19 +00004393 /* Use F_GETLK to determine the locks other processes are holding
4394 ** on the DMS byte. If it indicates that another process is holding
4395 ** a SHARED lock, then this process may also take a SHARED lock
4396 ** and proceed with opening the *-shm file.
4397 **
4398 ** Or, if no other process is holding any lock, then this process
4399 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4400 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4401 ** downgrade to a SHARED lock on the DMS byte.
4402 **
4403 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4404 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4405 ** version of this code attempted the SHARED lock at this point. But
4406 ** this introduced a subtle race condition: if the process holding
4407 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4408 ** process might open and use the *-shm file without truncating it.
4409 ** And if the *-shm file has been corrupted by a power failure or
4410 ** system crash, the database itself may also become corrupt. */
drh66dfec8b2011-06-01 20:01:49 +00004411 rc = SQLITE_OK;
dan176b2a92017-11-01 06:59:19 +00004412 lock.l_whence = SEEK_SET;
4413 lock.l_start = UNIX_SHM_DMS;
4414 lock.l_len = 1;
4415 lock.l_type = F_WRLCK;
4416 if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
4417 rc = SQLITE_IOERR_LOCK;
4418 }else if( lock.l_type==F_UNLCK ){
4419 if( pShmNode->isReadonly ){
drhb5039fb2017-10-25 23:28:13 +00004420 rc = SQLITE_CANTOPEN_DIRTYWAL;
dan176b2a92017-11-01 06:59:19 +00004421 }else{
4422 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
4423 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
4424 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
4425 }
drhb5039fb2017-10-25 23:28:13 +00004426 }
dan176b2a92017-11-01 06:59:19 +00004427 }else if( lock.l_type==F_WRLCK ){
4428 rc = SQLITE_BUSY;
drh3cb93392011-03-12 18:10:44 +00004429 }
dan176b2a92017-11-01 06:59:19 +00004430
drh66dfec8b2011-06-01 20:01:49 +00004431 if( rc==SQLITE_OK ){
dan176b2a92017-11-01 06:59:19 +00004432 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
drhbbf76ee2015-03-10 20:22:35 +00004433 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004434 }
4435 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004436 }
drhd9e5c4f2010-05-12 18:01:39 +00004437 }
4438
drhd91c68f2010-05-14 14:52:25 +00004439 /* Make the new connection a child of the unixShmNode */
4440 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004441#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004442 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004443#endif
drhd91c68f2010-05-14 14:52:25 +00004444 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004445 pDbFd->pShm = p;
4446 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004447
4448 /* The reference count on pShmNode has already been incremented under
4449 ** the cover of the unixEnterMutex() mutex and the pointer from the
4450 ** new (struct unixShm) object to the pShmNode has been set. All that is
4451 ** left to do is to link the new object into the linked list starting
4452 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4453 ** mutex.
4454 */
4455 sqlite3_mutex_enter(pShmNode->mutex);
4456 p->pNext = pShmNode->pFirst;
4457 pShmNode->pFirst = p;
4458 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004459 return SQLITE_OK;
4460
4461 /* Jump here on any error */
4462shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004463 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004464 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004465 unixLeaveMutex();
4466 return rc;
4467}
4468
4469/*
danda9fe0c2010-07-13 18:44:03 +00004470** This function is called to obtain a pointer to region iRegion of the
4471** shared-memory associated with the database file fd. Shared-memory regions
4472** are numbered starting from zero. Each shared-memory region is szRegion
4473** bytes in size.
4474**
4475** If an error occurs, an error code is returned and *pp is set to NULL.
4476**
4477** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4478** region has not been allocated (by any client, including one running in a
4479** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4480** bExtend is non-zero and the requested shared-memory region has not yet
4481** been allocated, it is allocated by this function.
4482**
4483** If the shared-memory region has already been allocated or is allocated by
4484** this call as described above, then it is mapped into this processes
4485** address space (if it is not already), *pp is set to point to the mapped
4486** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004487*/
danda9fe0c2010-07-13 18:44:03 +00004488static int unixShmMap(
4489 sqlite3_file *fd, /* Handle open on database file */
4490 int iRegion, /* Region to retrieve */
4491 int szRegion, /* Size of regions */
4492 int bExtend, /* True to extend file if necessary */
4493 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004494){
danda9fe0c2010-07-13 18:44:03 +00004495 unixFile *pDbFd = (unixFile*)fd;
4496 unixShm *p;
4497 unixShmNode *pShmNode;
4498 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004499 int nShmPerMap = unixShmRegionPerMap();
4500 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004501
danda9fe0c2010-07-13 18:44:03 +00004502 /* If the shared-memory file has not yet been opened, open it now. */
4503 if( pDbFd->pShm==0 ){
4504 rc = unixOpenSharedMemory(pDbFd);
4505 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004506 }
drhd9e5c4f2010-05-12 18:01:39 +00004507
danda9fe0c2010-07-13 18:44:03 +00004508 p = pDbFd->pShm;
4509 pShmNode = p->pShmNode;
4510 sqlite3_mutex_enter(pShmNode->mutex);
4511 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004512 assert( pShmNode->pInode==pDbFd->pInode );
4513 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4514 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004515
dan781e34c2014-03-20 08:59:47 +00004516 /* Minimum number of regions required to be mapped. */
4517 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4518
4519 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004520 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004521 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004522 struct stat sStat; /* Used by fstat() */
4523
4524 pShmNode->szRegion = szRegion;
4525
drh3cb93392011-03-12 18:10:44 +00004526 if( pShmNode->h>=0 ){
4527 /* The requested region is not mapped into this processes address space.
4528 ** Check to see if it has been allocated (i.e. if the wal-index file is
4529 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004530 */
drh3cb93392011-03-12 18:10:44 +00004531 if( osFstat(pShmNode->h, &sStat) ){
4532 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004533 goto shmpage_out;
4534 }
drh3cb93392011-03-12 18:10:44 +00004535
4536 if( sStat.st_size<nByte ){
4537 /* The requested memory region does not exist. If bExtend is set to
4538 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004539 */
dan47a2b4a2013-04-26 16:09:29 +00004540 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004541 goto shmpage_out;
4542 }
dan47a2b4a2013-04-26 16:09:29 +00004543
4544 /* Alternatively, if bExtend is true, extend the file. Do this by
4545 ** writing a single byte to the end of each (OS) page being
4546 ** allocated or extended. Technically, we need only write to the
4547 ** last page in order to extend the file. But writing to all new
4548 ** pages forces the OS to allocate them immediately, which reduces
4549 ** the chances of SIGBUS while accessing the mapped region later on.
4550 */
4551 else{
4552 static const int pgsz = 4096;
4553 int iPg;
4554
4555 /* Write to the last byte of each newly allocated or extended page */
4556 assert( (nByte % pgsz)==0 );
4557 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004558 int x = 0;
4559 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004560 const char *zFile = pShmNode->zFilename;
4561 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4562 goto shmpage_out;
4563 }
4564 }
drh3cb93392011-03-12 18:10:44 +00004565 }
4566 }
danda9fe0c2010-07-13 18:44:03 +00004567 }
4568
4569 /* Map the requested memory region into this processes address space. */
4570 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004571 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004572 );
4573 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004574 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004575 goto shmpage_out;
4576 }
4577 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004578 while( pShmNode->nRegion<nReqRegion ){
4579 int nMap = szRegion*nShmPerMap;
4580 int i;
drh3cb93392011-03-12 18:10:44 +00004581 void *pMem;
4582 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004583 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004584 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004585 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004586 );
4587 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004588 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004589 goto shmpage_out;
4590 }
4591 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004592 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004593 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004594 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004595 goto shmpage_out;
4596 }
4597 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004598 }
dan781e34c2014-03-20 08:59:47 +00004599
4600 for(i=0; i<nShmPerMap; i++){
4601 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4602 }
4603 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004604 }
4605 }
4606
4607shmpage_out:
4608 if( pShmNode->nRegion>iRegion ){
4609 *pp = pShmNode->apRegion[iRegion];
4610 }else{
4611 *pp = 0;
4612 }
drh66dfec8b2011-06-01 20:01:49 +00004613 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004614 sqlite3_mutex_leave(pShmNode->mutex);
4615 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004616}
4617
4618/*
drhd9e5c4f2010-05-12 18:01:39 +00004619** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004620**
4621** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4622** different here than in posix. In xShmLock(), one can go from unlocked
4623** to shared and back or from unlocked to exclusive and back. But one may
4624** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004625*/
4626static int unixShmLock(
4627 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004628 int ofst, /* First lock to acquire or release */
4629 int n, /* Number of locks to acquire or release */
4630 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004631){
drh73b64e42010-05-30 19:55:15 +00004632 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4633 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4634 unixShm *pX; /* For looping over all siblings */
4635 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4636 int rc = SQLITE_OK; /* Result code */
4637 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004638
drhd91c68f2010-05-14 14:52:25 +00004639 assert( pShmNode==pDbFd->pInode->pShmNode );
4640 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004641 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004642 assert( n>=1 );
4643 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4644 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4645 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4646 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4647 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004648 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4649 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004650
drhc99597c2010-05-31 01:41:15 +00004651 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004652 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004653 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004654 if( flags & SQLITE_SHM_UNLOCK ){
4655 u16 allMask = 0; /* Mask of locks held by siblings */
4656
4657 /* See if any siblings hold this same lock */
4658 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4659 if( pX==p ) continue;
4660 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4661 allMask |= pX->sharedMask;
4662 }
4663
4664 /* Unlock the system-level locks */
4665 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004666 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004667 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004668 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004669 }
drh73b64e42010-05-30 19:55:15 +00004670
4671 /* Undo the local locks */
4672 if( rc==SQLITE_OK ){
4673 p->exclMask &= ~mask;
4674 p->sharedMask &= ~mask;
4675 }
4676 }else if( flags & SQLITE_SHM_SHARED ){
4677 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4678
4679 /* Find out which shared locks are already held by sibling connections.
4680 ** If any sibling already holds an exclusive lock, go ahead and return
4681 ** SQLITE_BUSY.
4682 */
4683 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004684 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004685 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004686 break;
4687 }
4688 allShared |= pX->sharedMask;
4689 }
4690
4691 /* Get shared locks at the system level, if necessary */
4692 if( rc==SQLITE_OK ){
4693 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004694 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004695 }else{
drh73b64e42010-05-30 19:55:15 +00004696 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004697 }
drhd9e5c4f2010-05-12 18:01:39 +00004698 }
drh73b64e42010-05-30 19:55:15 +00004699
4700 /* Get the local shared locks */
4701 if( rc==SQLITE_OK ){
4702 p->sharedMask |= mask;
4703 }
4704 }else{
4705 /* Make sure no sibling connections hold locks that will block this
4706 ** lock. If any do, return SQLITE_BUSY right away.
4707 */
4708 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004709 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4710 rc = SQLITE_BUSY;
4711 break;
4712 }
4713 }
4714
4715 /* Get the exclusive locks at the system level. Then if successful
4716 ** also mark the local connection as being locked.
4717 */
4718 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004719 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004720 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004721 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004722 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004723 }
drhd9e5c4f2010-05-12 18:01:39 +00004724 }
4725 }
drhd91c68f2010-05-14 14:52:25 +00004726 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004727 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004728 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004729 return rc;
4730}
4731
drh286a2882010-05-20 23:51:06 +00004732/*
4733** Implement a memory barrier or memory fence on shared memory.
4734**
4735** All loads and stores begun before the barrier must complete before
4736** any load or store begun after the barrier.
4737*/
4738static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004739 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004740){
drhff828942010-06-26 21:34:06 +00004741 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004742 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4743 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004744 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004745}
4746
dan18801912010-06-14 14:07:50 +00004747/*
danda9fe0c2010-07-13 18:44:03 +00004748** Close a connection to shared-memory. Delete the underlying
4749** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004750**
4751** If there is no shared memory associated with the connection then this
4752** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004753*/
danda9fe0c2010-07-13 18:44:03 +00004754static int unixShmUnmap(
4755 sqlite3_file *fd, /* The underlying database file */
4756 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004757){
danda9fe0c2010-07-13 18:44:03 +00004758 unixShm *p; /* The connection to be closed */
4759 unixShmNode *pShmNode; /* The underlying shared-memory file */
4760 unixShm **pp; /* For looping over sibling connections */
4761 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004762
danda9fe0c2010-07-13 18:44:03 +00004763 pDbFd = (unixFile*)fd;
4764 p = pDbFd->pShm;
4765 if( p==0 ) return SQLITE_OK;
4766 pShmNode = p->pShmNode;
4767
4768 assert( pShmNode==pDbFd->pInode->pShmNode );
4769 assert( pShmNode->pInode==pDbFd->pInode );
4770
4771 /* Remove connection p from the set of connections associated
4772 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004773 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004774 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4775 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004776
danda9fe0c2010-07-13 18:44:03 +00004777 /* Free the connection p */
4778 sqlite3_free(p);
4779 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004780 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004781
4782 /* If pShmNode->nRef has reached 0, then close the underlying
4783 ** shared-memory file, too */
4784 unixEnterMutex();
4785 assert( pShmNode->nRef>0 );
4786 pShmNode->nRef--;
4787 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004788 if( deleteFlag && pShmNode->h>=0 ){
4789 osUnlink(pShmNode->zFilename);
4790 }
danda9fe0c2010-07-13 18:44:03 +00004791 unixShmPurge(pDbFd);
4792 }
4793 unixLeaveMutex();
4794
4795 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004796}
drh286a2882010-05-20 23:51:06 +00004797
danda9fe0c2010-07-13 18:44:03 +00004798
drhd9e5c4f2010-05-12 18:01:39 +00004799#else
drh6b017cc2010-06-14 18:01:46 +00004800# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004801# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004802# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004803# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004804#endif /* #ifndef SQLITE_OMIT_WAL */
4805
mistachkine98844f2013-08-24 00:59:24 +00004806#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004807/*
danaef49d72013-03-25 16:28:54 +00004808** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004809*/
danf23da962013-03-23 21:00:41 +00004810static void unixUnmapfile(unixFile *pFd){
4811 assert( pFd->nFetchOut==0 );
4812 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004813 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004814 pFd->pMapRegion = 0;
4815 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004816 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004817 }
4818}
dan5d8a1372013-03-19 19:28:06 +00004819
danaef49d72013-03-25 16:28:54 +00004820/*
dane6ecd662013-04-01 17:56:59 +00004821** Attempt to set the size of the memory mapping maintained by file
4822** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4823**
4824** If successful, this function sets the following variables:
4825**
4826** unixFile.pMapRegion
4827** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004828** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004829**
4830** If unsuccessful, an error message is logged via sqlite3_log() and
4831** the three variables above are zeroed. In this case SQLite should
4832** continue accessing the database using the xRead() and xWrite()
4833** methods.
4834*/
4835static void unixRemapfile(
4836 unixFile *pFd, /* File descriptor object */
4837 i64 nNew /* Required mapping size */
4838){
dan4ff7bc42013-04-02 12:04:09 +00004839 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004840 int h = pFd->h; /* File descriptor open on db file */
4841 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004842 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004843 u8 *pNew = 0; /* Location of new mapping */
4844 int flags = PROT_READ; /* Flags to pass to mmap() */
4845
4846 assert( pFd->nFetchOut==0 );
4847 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004848 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004849 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004850 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004851 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004852
danfe33e392015-11-17 20:56:06 +00004853#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004854 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004855#endif
dane6ecd662013-04-01 17:56:59 +00004856
4857 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004858#if HAVE_MREMAP
4859 i64 nReuse = pFd->mmapSize;
4860#else
danbc760632014-03-20 09:42:09 +00004861 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004862 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004863#endif
dane6ecd662013-04-01 17:56:59 +00004864 u8 *pReq = &pOrig[nReuse];
4865
4866 /* Unmap any pages of the existing mapping that cannot be reused. */
4867 if( nReuse!=nOrig ){
4868 osMunmap(pReq, nOrig-nReuse);
4869 }
4870
4871#if HAVE_MREMAP
4872 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004873 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004874#else
4875 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4876 if( pNew!=MAP_FAILED ){
4877 if( pNew!=pReq ){
4878 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004879 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004880 }else{
4881 pNew = pOrig;
4882 }
4883 }
4884#endif
4885
dan48ccef82013-04-02 20:55:01 +00004886 /* The attempt to extend the existing mapping failed. Free it. */
4887 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004888 osMunmap(pOrig, nReuse);
4889 }
4890 }
4891
4892 /* If pNew is still NULL, try to create an entirely new mapping. */
4893 if( pNew==0 ){
4894 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004895 }
4896
dan4ff7bc42013-04-02 12:04:09 +00004897 if( pNew==MAP_FAILED ){
4898 pNew = 0;
4899 nNew = 0;
4900 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4901
4902 /* If the mmap() above failed, assume that all subsequent mmap() calls
4903 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4904 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004905 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004906 }
dane6ecd662013-04-01 17:56:59 +00004907 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004908 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004909}
4910
4911/*
danaef49d72013-03-25 16:28:54 +00004912** Memory map or remap the file opened by file-descriptor pFd (if the file
4913** is already mapped, the existing mapping is replaced by the new). Or, if
4914** there already exists a mapping for this file, and there are still
4915** outstanding xFetch() references to it, this function is a no-op.
4916**
4917** If parameter nByte is non-negative, then it is the requested size of
4918** the mapping to create. Otherwise, if nByte is less than zero, then the
4919** requested size is the size of the file on disk. The actual size of the
4920** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004921** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004922**
4923** SQLITE_OK is returned if no error occurs (even if the mapping is not
4924** recreated as a result of outstanding references) or an SQLite error
4925** code otherwise.
4926*/
drhf3b1ed02015-12-02 13:11:03 +00004927static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004928 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004929 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004930 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4931
4932 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004933 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004934 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004935 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004936 }
drh3044b512014-06-16 16:41:52 +00004937 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004938 }
drh9b4c59f2013-04-15 17:03:42 +00004939 if( nMap>pFd->mmapSizeMax ){
4940 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004941 }
4942
drh333e6ca2015-12-02 15:44:39 +00004943 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004944 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004945 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004946 }
4947
danf23da962013-03-23 21:00:41 +00004948 return SQLITE_OK;
4949}
mistachkine98844f2013-08-24 00:59:24 +00004950#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004951
danaef49d72013-03-25 16:28:54 +00004952/*
4953** If possible, return a pointer to a mapping of file fd starting at offset
4954** iOff. The mapping must be valid for at least nAmt bytes.
4955**
4956** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4957** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4958** Finally, if an error does occur, return an SQLite error code. The final
4959** value of *pp is undefined in this case.
4960**
4961** If this function does return a pointer, the caller must eventually
4962** release the reference by calling unixUnfetch().
4963*/
danf23da962013-03-23 21:00:41 +00004964static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004965#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004966 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004967#endif
danf23da962013-03-23 21:00:41 +00004968 *pp = 0;
4969
drh9b4c59f2013-04-15 17:03:42 +00004970#if SQLITE_MAX_MMAP_SIZE>0
4971 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004972 if( pFd->pMapRegion==0 ){
4973 int rc = unixMapfile(pFd, -1);
4974 if( rc!=SQLITE_OK ) return rc;
4975 }
4976 if( pFd->mmapSize >= iOff+nAmt ){
4977 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4978 pFd->nFetchOut++;
4979 }
4980 }
drh6e0b6d52013-04-09 16:19:20 +00004981#endif
danf23da962013-03-23 21:00:41 +00004982 return SQLITE_OK;
4983}
4984
danaef49d72013-03-25 16:28:54 +00004985/*
dandf737fe2013-03-25 17:00:24 +00004986** If the third argument is non-NULL, then this function releases a
4987** reference obtained by an earlier call to unixFetch(). The second
4988** argument passed to this function must be the same as the corresponding
4989** argument that was passed to the unixFetch() invocation.
4990**
4991** Or, if the third argument is NULL, then this function is being called
4992** to inform the VFS layer that, according to POSIX, any existing mapping
4993** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004994*/
dandf737fe2013-03-25 17:00:24 +00004995static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004996#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004997 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004998 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004999
danaef49d72013-03-25 16:28:54 +00005000 /* If p==0 (unmap the entire file) then there must be no outstanding
5001 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5002 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005003 assert( (p==0)==(pFd->nFetchOut==0) );
5004
dandf737fe2013-03-25 17:00:24 +00005005 /* If p!=0, it must match the iOff value. */
5006 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5007
danf23da962013-03-23 21:00:41 +00005008 if( p ){
5009 pFd->nFetchOut--;
5010 }else{
5011 unixUnmapfile(pFd);
5012 }
5013
5014 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005015#else
5016 UNUSED_PARAMETER(fd);
5017 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005018 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005019#endif
danf23da962013-03-23 21:00:41 +00005020 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005021}
5022
5023/*
drh734c9862008-11-28 15:37:20 +00005024** Here ends the implementation of all sqlite3_file methods.
5025**
5026********************** End sqlite3_file Methods *******************************
5027******************************************************************************/
5028
5029/*
drh6b9d6dd2008-12-03 19:34:47 +00005030** This division contains definitions of sqlite3_io_methods objects that
5031** implement various file locking strategies. It also contains definitions
5032** of "finder" functions. A finder-function is used to locate the appropriate
5033** sqlite3_io_methods object for a particular database file. The pAppData
5034** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5035** the correct finder-function for that VFS.
5036**
5037** Most finder functions return a pointer to a fixed sqlite3_io_methods
5038** object. The only interesting finder-function is autolockIoFinder, which
5039** looks at the filesystem type and tries to guess the best locking
5040** strategy from that.
5041**
peter.d.reid60ec9142014-09-06 16:39:46 +00005042** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005043**
5044** (1) The real finder-function named "FImpt()".
5045**
dane946c392009-08-22 11:39:46 +00005046** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005047**
5048**
5049** A pointer to the F pointer is used as the pAppData value for VFS
5050** objects. We have to do this instead of letting pAppData point
5051** directly at the finder-function since C90 rules prevent a void*
5052** from be cast into a function pointer.
5053**
drh6b9d6dd2008-12-03 19:34:47 +00005054**
drh7708e972008-11-29 00:56:52 +00005055** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005056**
drh7708e972008-11-29 00:56:52 +00005057** * A constant sqlite3_io_methods object call METHOD that has locking
5058** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5059**
5060** * An I/O method finder function called FINDER that returns a pointer
5061** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005062*/
drhe6d41732015-02-21 00:49:00 +00005063#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005064static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005065 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005066 CLOSE, /* xClose */ \
5067 unixRead, /* xRead */ \
5068 unixWrite, /* xWrite */ \
5069 unixTruncate, /* xTruncate */ \
5070 unixSync, /* xSync */ \
5071 unixFileSize, /* xFileSize */ \
5072 LOCK, /* xLock */ \
5073 UNLOCK, /* xUnlock */ \
5074 CKLOCK, /* xCheckReservedLock */ \
5075 unixFileControl, /* xFileControl */ \
5076 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005077 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005078 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005079 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005080 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005081 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005082 unixFetch, /* xFetch */ \
5083 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005084}; \
drh0c2694b2009-09-03 16:23:44 +00005085static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5086 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005087 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005088} \
drh0c2694b2009-09-03 16:23:44 +00005089static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005090 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005091
5092/*
5093** Here are all of the sqlite3_io_methods objects for each of the
5094** locking strategies. Functions that return pointers to these methods
5095** are also created.
5096*/
5097IOMETHODS(
5098 posixIoFinder, /* Finder function name */
5099 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005100 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005101 unixClose, /* xClose method */
5102 unixLock, /* xLock method */
5103 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005104 unixCheckReservedLock, /* xCheckReservedLock method */
5105 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005106)
drh7708e972008-11-29 00:56:52 +00005107IOMETHODS(
5108 nolockIoFinder, /* Finder function name */
5109 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005110 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005111 nolockClose, /* xClose method */
5112 nolockLock, /* xLock method */
5113 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005114 nolockCheckReservedLock, /* xCheckReservedLock method */
5115 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005116)
drh7708e972008-11-29 00:56:52 +00005117IOMETHODS(
5118 dotlockIoFinder, /* Finder function name */
5119 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005120 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005121 dotlockClose, /* xClose method */
5122 dotlockLock, /* xLock method */
5123 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005124 dotlockCheckReservedLock, /* xCheckReservedLock method */
5125 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005126)
drh7708e972008-11-29 00:56:52 +00005127
drhe89b2912015-03-03 20:42:01 +00005128#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005129IOMETHODS(
5130 flockIoFinder, /* Finder function name */
5131 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005132 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005133 flockClose, /* xClose method */
5134 flockLock, /* xLock method */
5135 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005136 flockCheckReservedLock, /* xCheckReservedLock method */
5137 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005138)
drh7708e972008-11-29 00:56:52 +00005139#endif
5140
drh6c7d5c52008-11-21 20:32:33 +00005141#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005142IOMETHODS(
5143 semIoFinder, /* Finder function name */
5144 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005145 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005146 semXClose, /* xClose method */
5147 semXLock, /* xLock method */
5148 semXUnlock, /* xUnlock method */
5149 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005150 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005151)
aswiftaebf4132008-11-21 00:10:35 +00005152#endif
drh7708e972008-11-29 00:56:52 +00005153
drhd2cb50b2009-01-09 21:41:17 +00005154#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005155IOMETHODS(
5156 afpIoFinder, /* Finder function name */
5157 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005158 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005159 afpClose, /* xClose method */
5160 afpLock, /* xLock method */
5161 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005162 afpCheckReservedLock, /* xCheckReservedLock method */
5163 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005164)
drh715ff302008-12-03 22:32:44 +00005165#endif
5166
5167/*
5168** The proxy locking method is a "super-method" in the sense that it
5169** opens secondary file descriptors for the conch and lock files and
5170** it uses proxy, dot-file, AFP, and flock() locking methods on those
5171** secondary files. For this reason, the division that implements
5172** proxy locking is located much further down in the file. But we need
5173** to go ahead and define the sqlite3_io_methods and finder function
5174** for proxy locking here. So we forward declare the I/O methods.
5175*/
drhd2cb50b2009-01-09 21:41:17 +00005176#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005177static int proxyClose(sqlite3_file*);
5178static int proxyLock(sqlite3_file*, int);
5179static int proxyUnlock(sqlite3_file*, int);
5180static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005181IOMETHODS(
5182 proxyIoFinder, /* Finder function name */
5183 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005184 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005185 proxyClose, /* xClose method */
5186 proxyLock, /* xLock method */
5187 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005188 proxyCheckReservedLock, /* xCheckReservedLock method */
5189 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005190)
aswiftaebf4132008-11-21 00:10:35 +00005191#endif
drh7708e972008-11-29 00:56:52 +00005192
drh7ed97b92010-01-20 13:07:21 +00005193/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5194#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5195IOMETHODS(
5196 nfsIoFinder, /* Finder function name */
5197 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005198 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005199 unixClose, /* xClose method */
5200 unixLock, /* xLock method */
5201 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005202 unixCheckReservedLock, /* xCheckReservedLock method */
5203 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005204)
5205#endif
drh7708e972008-11-29 00:56:52 +00005206
drhd2cb50b2009-01-09 21:41:17 +00005207#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005208/*
drh6b9d6dd2008-12-03 19:34:47 +00005209** This "finder" function attempts to determine the best locking strategy
5210** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005211** object that implements that strategy.
5212**
5213** This is for MacOSX only.
5214*/
drh1875f7a2008-12-08 18:19:17 +00005215static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005216 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005217 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005218){
5219 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005220 const char *zFilesystem; /* Filesystem type name */
5221 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005222 } aMap[] = {
5223 { "hfs", &posixIoMethods },
5224 { "ufs", &posixIoMethods },
5225 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005226 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005227 { "webdav", &nolockIoMethods },
5228 { 0, 0 }
5229 };
5230 int i;
5231 struct statfs fsInfo;
5232 struct flock lockInfo;
5233
5234 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005235 /* If filePath==NULL that means we are dealing with a transient file
5236 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005237 return &nolockIoMethods;
5238 }
5239 if( statfs(filePath, &fsInfo) != -1 ){
5240 if( fsInfo.f_flags & MNT_RDONLY ){
5241 return &nolockIoMethods;
5242 }
5243 for(i=0; aMap[i].zFilesystem; i++){
5244 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5245 return aMap[i].pMethods;
5246 }
5247 }
5248 }
5249
5250 /* Default case. Handles, amongst others, "nfs".
5251 ** Test byte-range lock using fcntl(). If the call succeeds,
5252 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005253 */
drh7708e972008-11-29 00:56:52 +00005254 lockInfo.l_len = 1;
5255 lockInfo.l_start = 0;
5256 lockInfo.l_whence = SEEK_SET;
5257 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005258 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005259 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5260 return &nfsIoMethods;
5261 } else {
5262 return &posixIoMethods;
5263 }
drh7708e972008-11-29 00:56:52 +00005264 }else{
5265 return &dotlockIoMethods;
5266 }
5267}
drh0c2694b2009-09-03 16:23:44 +00005268static const sqlite3_io_methods
5269 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005270
drhd2cb50b2009-01-09 21:41:17 +00005271#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005272
drhe89b2912015-03-03 20:42:01 +00005273#if OS_VXWORKS
5274/*
5275** This "finder" function for VxWorks checks to see if posix advisory
5276** locking works. If it does, then that is what is used. If it does not
5277** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005278*/
drhe89b2912015-03-03 20:42:01 +00005279static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005280 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005281 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005282){
5283 struct flock lockInfo;
5284
5285 if( !filePath ){
5286 /* If filePath==NULL that means we are dealing with a transient file
5287 ** that does not need to be locked. */
5288 return &nolockIoMethods;
5289 }
5290
5291 /* Test if fcntl() is supported and use POSIX style locks.
5292 ** Otherwise fall back to the named semaphore method.
5293 */
5294 lockInfo.l_len = 1;
5295 lockInfo.l_start = 0;
5296 lockInfo.l_whence = SEEK_SET;
5297 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005298 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005299 return &posixIoMethods;
5300 }else{
5301 return &semIoMethods;
5302 }
5303}
drh0c2694b2009-09-03 16:23:44 +00005304static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005305 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005306
drhe89b2912015-03-03 20:42:01 +00005307#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005308
drh7708e972008-11-29 00:56:52 +00005309/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005310** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005311*/
drh0c2694b2009-09-03 16:23:44 +00005312typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005313
aswiftaebf4132008-11-21 00:10:35 +00005314
drh734c9862008-11-28 15:37:20 +00005315/****************************************************************************
5316**************************** sqlite3_vfs methods ****************************
5317**
5318** This division contains the implementation of methods on the
5319** sqlite3_vfs object.
5320*/
5321
danielk1977a3d4c882007-03-23 10:08:38 +00005322/*
danielk1977e339d652008-06-28 11:23:00 +00005323** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005324*/
5325static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005326 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005327 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005328 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005329 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005330 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005331){
drh7708e972008-11-29 00:56:52 +00005332 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005333 unixFile *pNew = (unixFile *)pId;
5334 int rc = SQLITE_OK;
5335
drh8af6c222010-05-14 12:43:01 +00005336 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005337
drhb07028f2011-10-14 21:49:18 +00005338 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005339 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005340
drh308c2a52010-05-14 11:30:18 +00005341 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005342 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005343 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005344 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005345 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005346#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005347 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005348#endif
drhc02a43a2012-01-10 23:18:38 +00005349 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5350 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005351 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005352 }
drh503a6862013-03-01 01:07:17 +00005353 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005354 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005355 }
drh339eb0b2008-03-07 15:34:11 +00005356
drh6c7d5c52008-11-21 20:32:33 +00005357#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005358 pNew->pId = vxworksFindFileId(zFilename);
5359 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005360 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005361 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005362 }
5363#endif
5364
drhc02a43a2012-01-10 23:18:38 +00005365 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005366 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005367 }else{
drh0c2694b2009-09-03 16:23:44 +00005368 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005369#if SQLITE_ENABLE_LOCKING_STYLE
5370 /* Cache zFilename in the locking context (AFP and dotlock override) for
5371 ** proxyLock activation is possible (remote proxy is based on db name)
5372 ** zFilename remains valid until file is closed, to support */
5373 pNew->lockingContext = (void*)zFilename;
5374#endif
drhda0e7682008-07-30 15:27:54 +00005375 }
danielk1977e339d652008-06-28 11:23:00 +00005376
drh7ed97b92010-01-20 13:07:21 +00005377 if( pLockingStyle == &posixIoMethods
5378#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5379 || pLockingStyle == &nfsIoMethods
5380#endif
5381 ){
drh7708e972008-11-29 00:56:52 +00005382 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005383 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005384 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005385 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005386 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005387 ** in two scenarios:
5388 **
5389 ** (a) A call to fstat() failed.
5390 ** (b) A malloc failed.
5391 **
5392 ** Scenario (b) may only occur if the process is holding no other
5393 ** file descriptors open on the same file. If there were other file
5394 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005395 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005396 ** handle h - as it is guaranteed that no posix locks will be released
5397 ** by doing so.
5398 **
5399 ** If scenario (a) caused the error then things are not so safe. The
5400 ** implicit assumption here is that if fstat() fails, things are in
5401 ** such bad shape that dropping a lock or two doesn't matter much.
5402 */
drh0e9365c2011-03-02 02:08:13 +00005403 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005404 h = -1;
5405 }
drh7708e972008-11-29 00:56:52 +00005406 unixLeaveMutex();
5407 }
danielk1977e339d652008-06-28 11:23:00 +00005408
drhd2cb50b2009-01-09 21:41:17 +00005409#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005410 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005411 /* AFP locking uses the file path so it needs to be included in
5412 ** the afpLockingContext.
5413 */
5414 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005415 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005416 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005417 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005418 }else{
5419 /* NB: zFilename exists and remains valid until the file is closed
5420 ** according to requirement F11141. So we do not need to make a
5421 ** copy of the filename. */
5422 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005423 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005424 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005425 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005426 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005427 if( rc!=SQLITE_OK ){
5428 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005429 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005430 h = -1;
5431 }
drh7708e972008-11-29 00:56:52 +00005432 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005433 }
drh7708e972008-11-29 00:56:52 +00005434 }
5435#endif
danielk1977e339d652008-06-28 11:23:00 +00005436
drh7708e972008-11-29 00:56:52 +00005437 else if( pLockingStyle == &dotlockIoMethods ){
5438 /* Dotfile locking uses the file path so it needs to be included in
5439 ** the dotlockLockingContext
5440 */
5441 char *zLockFile;
5442 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005443 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005444 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005445 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005446 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005447 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005448 }else{
5449 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005450 }
drh7708e972008-11-29 00:56:52 +00005451 pNew->lockingContext = zLockFile;
5452 }
danielk1977e339d652008-06-28 11:23:00 +00005453
drh6c7d5c52008-11-21 20:32:33 +00005454#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005455 else if( pLockingStyle == &semIoMethods ){
5456 /* Named semaphore locking uses the file path so it needs to be
5457 ** included in the semLockingContext
5458 */
5459 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005460 rc = findInodeInfo(pNew, &pNew->pInode);
5461 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5462 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005463 int n;
drh2238dcc2009-08-27 17:56:20 +00005464 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005465 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005466 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005467 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005468 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5469 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005470 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005471 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005472 }
chw97185482008-11-17 08:05:31 +00005473 }
drh7708e972008-11-29 00:56:52 +00005474 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005475 }
drh7708e972008-11-29 00:56:52 +00005476#endif
aswift5b1a2562008-08-22 00:22:35 +00005477
drh4bf66fd2015-02-19 02:43:02 +00005478 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005479#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005480 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005481 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005482 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005483 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005484 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005485 }
chw97185482008-11-17 08:05:31 +00005486#endif
danielk1977e339d652008-06-28 11:23:00 +00005487 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005488 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005489 }else{
drh7708e972008-11-29 00:56:52 +00005490 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005491 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005492 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005493 }
danielk1977e339d652008-06-28 11:23:00 +00005494 return rc;
drh054889e2005-11-30 03:20:31 +00005495}
drh9c06c952005-11-26 00:25:00 +00005496
danielk1977ad94b582007-08-20 06:44:22 +00005497/*
drh8b3cf822010-06-01 21:02:51 +00005498** Return the name of a directory in which to put temporary files.
5499** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005500*/
drh7234c6d2010-06-19 15:10:09 +00005501static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005502 static const char *azDirs[] = {
5503 0,
aswiftaebf4132008-11-21 00:10:35 +00005504 0,
danielk197717b90b52008-06-06 11:11:25 +00005505 "/var/tmp",
5506 "/usr/tmp",
5507 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005508 "."
danielk197717b90b52008-06-06 11:11:25 +00005509 };
drh2aab11f2016-04-29 20:30:56 +00005510 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005511 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005512 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005513
drhb7e50ad2015-11-28 21:49:53 +00005514 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5515 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005516 while(1){
5517 if( zDir!=0
5518 && osStat(zDir, &buf)==0
5519 && S_ISDIR(buf.st_mode)
5520 && osAccess(zDir, 03)==0
5521 ){
5522 return zDir;
5523 }
5524 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5525 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005526 }
drh7694e062016-04-21 23:37:24 +00005527 return 0;
drh8b3cf822010-06-01 21:02:51 +00005528}
5529
5530/*
5531** Create a temporary file name in zBuf. zBuf must be allocated
5532** by the calling process and must be big enough to hold at least
5533** pVfs->mxPathname bytes.
5534*/
5535static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005536 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005537 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005538
5539 /* It's odd to simulate an io-error here, but really this is just
5540 ** using the io-error infrastructure to test that SQLite handles this
5541 ** function failing.
5542 */
drh7694e062016-04-21 23:37:24 +00005543 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005544 SimulateIOError( return SQLITE_IOERR );
5545
drh7234c6d2010-06-19 15:10:09 +00005546 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005547 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005548 do{
drh970942e2015-11-25 23:13:14 +00005549 u64 r;
5550 sqlite3_randomness(sizeof(r), &r);
5551 assert( nBuf>2 );
5552 zBuf[nBuf-2] = 0;
5553 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5554 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005555 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005556 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005557 return SQLITE_OK;
5558}
5559
drhd2cb50b2009-01-09 21:41:17 +00005560#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005561/*
5562** Routine to transform a unixFile into a proxy-locking unixFile.
5563** Implementation in the proxy-lock division, but used by unixOpen()
5564** if SQLITE_PREFER_PROXY_LOCKING is defined.
5565*/
5566static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005567#endif
drhc66d5b62008-12-03 22:48:32 +00005568
dan08da86a2009-08-21 17:18:03 +00005569/*
5570** Search for an unused file descriptor that was opened on the database
5571** file (not a journal or master-journal file) identified by pathname
5572** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5573** argument to this function.
5574**
5575** Such a file descriptor may exist if a database connection was closed
5576** but the associated file descriptor could not be closed because some
5577** other file descriptor open on the same file is holding a file-lock.
5578** Refer to comments in the unixClose() function and the lengthy comment
5579** describing "Posix Advisory Locking" at the start of this file for
5580** further details. Also, ticket #4018.
5581**
5582** If a suitable file descriptor is found, then it is returned. If no
5583** such file descriptor is located, -1 is returned.
5584*/
dane946c392009-08-22 11:39:46 +00005585static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5586 UnixUnusedFd *pUnused = 0;
5587
5588 /* Do not search for an unused file descriptor on vxworks. Not because
5589 ** vxworks would not benefit from the change (it might, we're not sure),
5590 ** but because no way to test it is currently available. It is better
5591 ** not to risk breaking vxworks support for the sake of such an obscure
5592 ** feature. */
5593#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005594 struct stat sStat; /* Results of stat() call */
5595
drhc68886b2017-08-18 16:09:52 +00005596 unixEnterMutex();
5597
dan08da86a2009-08-21 17:18:03 +00005598 /* A stat() call may fail for various reasons. If this happens, it is
5599 ** almost certain that an open() call on the same path will also fail.
5600 ** For this reason, if an error occurs in the stat() call here, it is
5601 ** ignored and -1 is returned. The caller will try to open a new file
5602 ** descriptor on the same path, fail, and return an error to SQLite.
5603 **
5604 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005605 ** not searching for a reusable file descriptor are not dire. */
drhc68886b2017-08-18 16:09:52 +00005606 if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005607 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005608
drh8af6c222010-05-14 12:43:01 +00005609 pInode = inodeList;
5610 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005611 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005612 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005613 }
drh8af6c222010-05-14 12:43:01 +00005614 if( pInode ){
dane946c392009-08-22 11:39:46 +00005615 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005616 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005617 pUnused = *pp;
5618 if( pUnused ){
drhc68886b2017-08-18 16:09:52 +00005619 nUnusedFd--;
dane946c392009-08-22 11:39:46 +00005620 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005621 }
5622 }
dan08da86a2009-08-21 17:18:03 +00005623 }
drhc68886b2017-08-18 16:09:52 +00005624 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005625#endif /* if !OS_VXWORKS */
5626 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005627}
danielk197717b90b52008-06-06 11:11:25 +00005628
5629/*
dan1bf4ca72016-08-11 18:05:47 +00005630** Find the mode, uid and gid of file zFile.
5631*/
5632static int getFileMode(
5633 const char *zFile, /* File name */
5634 mode_t *pMode, /* OUT: Permissions of zFile */
5635 uid_t *pUid, /* OUT: uid of zFile. */
5636 gid_t *pGid /* OUT: gid of zFile. */
5637){
5638 struct stat sStat; /* Output of stat() on database file */
5639 int rc = SQLITE_OK;
5640 if( 0==osStat(zFile, &sStat) ){
5641 *pMode = sStat.st_mode & 0777;
5642 *pUid = sStat.st_uid;
5643 *pGid = sStat.st_gid;
5644 }else{
5645 rc = SQLITE_IOERR_FSTAT;
5646 }
5647 return rc;
5648}
5649
5650/*
danddb0ac42010-07-14 14:48:58 +00005651** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005652** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005653** and a value suitable for passing as the third argument to open(2) is
5654** written to *pMode. If an IO error occurs, an SQLite error code is
5655** returned and the value of *pMode is not modified.
5656**
peter.d.reid60ec9142014-09-06 16:39:46 +00005657** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005658** an indication to robust_open() to create the file using
5659** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5660** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005661** this function queries the file-system for the permissions on the
5662** corresponding database file and sets *pMode to this value. Whenever
5663** possible, WAL and journal files are created using the same permissions
5664** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005665**
5666** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5667** original filename is unavailable. But 8_3_NAMES is only used for
5668** FAT filesystems and permissions do not matter there, so just use
5669** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005670*/
5671static int findCreateFileMode(
5672 const char *zPath, /* Path of file (possibly) being created */
5673 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005674 mode_t *pMode, /* OUT: Permissions to open file with */
5675 uid_t *pUid, /* OUT: uid to set on the file */
5676 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005677){
5678 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005679 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005680 *pUid = 0;
5681 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005682 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005683 char zDb[MAX_PATHNAME+1]; /* Database file path */
5684 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005685
dana0c989d2010-11-05 18:07:37 +00005686 /* zPath is a path to a WAL or journal file. The following block derives
5687 ** the path to the associated database file from zPath. This block handles
5688 ** the following naming conventions:
5689 **
5690 ** "<path to db>-journal"
5691 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005692 ** "<path to db>-journalNN"
5693 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005694 **
drhd337c5b2011-10-20 18:23:35 +00005695 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005696 ** used by the test_multiplex.c module.
5697 */
5698 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005699 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005700 /* In normal operation, the journal file name will always contain
5701 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5702 ** rollback journal specifies a master journal with a goofy name, then
5703 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005704 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005705 nDb--;
5706 }
danddb0ac42010-07-14 14:48:58 +00005707 memcpy(zDb, zPath, nDb);
5708 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005709
dan1bf4ca72016-08-11 18:05:47 +00005710 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005711 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5712 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005713 }else if( flags & SQLITE_OPEN_URI ){
5714 /* If this is a main database file and the file was opened using a URI
5715 ** filename, check for the "modeof" parameter. If present, interpret
5716 ** its value as a filename and try to copy the mode, uid and gid from
5717 ** that file. */
5718 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5719 if( z ){
5720 rc = getFileMode(z, pMode, pUid, pGid);
5721 }
danddb0ac42010-07-14 14:48:58 +00005722 }
5723 return rc;
5724}
5725
5726/*
danielk1977ad94b582007-08-20 06:44:22 +00005727** Open the file zPath.
5728**
danielk1977b4b47412007-08-17 15:53:36 +00005729** Previously, the SQLite OS layer used three functions in place of this
5730** one:
5731**
5732** sqlite3OsOpenReadWrite();
5733** sqlite3OsOpenReadOnly();
5734** sqlite3OsOpenExclusive();
5735**
5736** These calls correspond to the following combinations of flags:
5737**
5738** ReadWrite() -> (READWRITE | CREATE)
5739** ReadOnly() -> (READONLY)
5740** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5741**
5742** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5743** true, the file was configured to be automatically deleted when the
5744** file handle closed. To achieve the same effect using this new
5745** interface, add the DELETEONCLOSE flag to those specified above for
5746** OpenExclusive().
5747*/
5748static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005749 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5750 const char *zPath, /* Pathname of file to be opened */
5751 sqlite3_file *pFile, /* The file descriptor to be filled in */
5752 int flags, /* Input flags to control the opening */
5753 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005754){
dan08da86a2009-08-21 17:18:03 +00005755 unixFile *p = (unixFile *)pFile;
5756 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005757 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005758 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005759 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005760 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005761 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005762
5763 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5764 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5765 int isCreate = (flags & SQLITE_OPEN_CREATE);
5766 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5767 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005768#if SQLITE_ENABLE_LOCKING_STYLE
5769 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5770#endif
drh3d4435b2011-08-26 20:55:50 +00005771#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5772 struct statfs fsInfo;
5773#endif
danielk1977b4b47412007-08-17 15:53:36 +00005774
danielk1977fee2d252007-08-18 10:59:19 +00005775 /* If creating a master or main-file journal, this function will open
5776 ** a file-descriptor on the directory too. The first time unixSync()
5777 ** is called the directory file descriptor will be fsync()ed and close()d.
5778 */
drh0059eae2011-08-08 23:48:40 +00005779 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005780 eType==SQLITE_OPEN_MASTER_JOURNAL
5781 || eType==SQLITE_OPEN_MAIN_JOURNAL
5782 || eType==SQLITE_OPEN_WAL
5783 ));
danielk1977fee2d252007-08-18 10:59:19 +00005784
danielk197717b90b52008-06-06 11:11:25 +00005785 /* If argument zPath is a NULL pointer, this function is required to open
5786 ** a temporary file. Use this buffer to store the file name in.
5787 */
drhc02a43a2012-01-10 23:18:38 +00005788 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005789 const char *zName = zPath;
5790
danielk1977fee2d252007-08-18 10:59:19 +00005791 /* Check the following statements are true:
5792 **
5793 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5794 ** (b) if CREATE is set, then READWRITE must also be set, and
5795 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005796 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005797 */
danielk1977b4b47412007-08-17 15:53:36 +00005798 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005799 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005800 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005801 assert(isDelete==0 || isCreate);
5802
danddb0ac42010-07-14 14:48:58 +00005803 /* The main DB, main journal, WAL file and master journal are never
5804 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005805 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5806 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5807 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005808 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005809
danielk1977fee2d252007-08-18 10:59:19 +00005810 /* Assert that the upper layer has set one of the "file-type" flags. */
5811 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5812 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5813 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005814 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005815 );
5816
drhb00d8622014-01-01 15:18:36 +00005817 /* Detect a pid change and reset the PRNG. There is a race condition
5818 ** here such that two or more threads all trying to open databases at
5819 ** the same instant might all reset the PRNG. But multiple resets
5820 ** are harmless.
5821 */
drh5ac93652015-03-21 20:59:43 +00005822 if( randomnessPid!=osGetpid(0) ){
5823 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005824 sqlite3_randomness(0,0);
5825 }
5826
dan08da86a2009-08-21 17:18:03 +00005827 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005828
dan08da86a2009-08-21 17:18:03 +00005829 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005830 UnixUnusedFd *pUnused;
5831 pUnused = findReusableFd(zName, flags);
5832 if( pUnused ){
5833 fd = pUnused->fd;
5834 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005835 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005836 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005837 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005838 }
5839 }
drhc68886b2017-08-18 16:09:52 +00005840 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005841
5842 /* Database filenames are double-zero terminated if they are not
5843 ** URIs with parameters. Hence, they can always be passed into
5844 ** sqlite3_uri_parameter(). */
5845 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5846
dan08da86a2009-08-21 17:18:03 +00005847 }else if( !zName ){
5848 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005849 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005850 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005851 if( rc!=SQLITE_OK ){
5852 return rc;
5853 }
5854 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005855
5856 /* Generated temporary filenames are always double-zero terminated
5857 ** for use by sqlite3_uri_parameter(). */
5858 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005859 }
5860
dan08da86a2009-08-21 17:18:03 +00005861 /* Determine the value of the flags parameter passed to POSIX function
5862 ** open(). These must be calculated even if open() is not called, as
5863 ** they may be stored as part of the file handle and used by the
5864 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005865 if( isReadonly ) openFlags |= O_RDONLY;
5866 if( isReadWrite ) openFlags |= O_RDWR;
5867 if( isCreate ) openFlags |= O_CREAT;
5868 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5869 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005870
danielk1977b4b47412007-08-17 15:53:36 +00005871 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005872 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005873 uid_t uid; /* Userid for the file */
5874 gid_t gid; /* Groupid for the file */
5875 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005876 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00005877 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00005878 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005879 return rc;
5880 }
drhad4f1e52011-03-04 15:43:57 +00005881 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005882 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005883 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5884 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005885 /* Failed to open the file for read/write access. Try read-only. */
5886 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005887 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005888 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005889 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005890 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005891 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005892 }
5893 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005894 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005895 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005896 }
drhac7c3ac2012-02-11 19:23:48 +00005897
5898 /* If this process is running as root and if creating a new rollback
5899 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005900 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005901 */
5902 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005903 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005904 }
danielk1977b4b47412007-08-17 15:53:36 +00005905 }
dan08da86a2009-08-21 17:18:03 +00005906 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005907 if( pOutFlags ){
5908 *pOutFlags = flags;
5909 }
5910
drhc68886b2017-08-18 16:09:52 +00005911 if( p->pPreallocatedUnused ){
5912 p->pPreallocatedUnused->fd = fd;
5913 p->pPreallocatedUnused->flags = flags;
dane946c392009-08-22 11:39:46 +00005914 }
5915
danielk1977b4b47412007-08-17 15:53:36 +00005916 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005917#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005918 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005919#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5920 zPath = sqlite3_mprintf("%s", zName);
5921 if( zPath==0 ){
5922 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00005923 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00005924 }
chw97185482008-11-17 08:05:31 +00005925#else
drh036ac7f2011-08-08 23:18:05 +00005926 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005927#endif
danielk1977b4b47412007-08-17 15:53:36 +00005928 }
drh41022642008-11-21 00:24:42 +00005929#if SQLITE_ENABLE_LOCKING_STYLE
5930 else{
dan08da86a2009-08-21 17:18:03 +00005931 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005932 }
5933#endif
drh7ed97b92010-01-20 13:07:21 +00005934
5935#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005936 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005937 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005938 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005939 return SQLITE_IOERR_ACCESS;
5940 }
5941 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5942 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5943 }
drh4bf66fd2015-02-19 02:43:02 +00005944 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5945 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5946 }
drh7ed97b92010-01-20 13:07:21 +00005947#endif
drhc02a43a2012-01-10 23:18:38 +00005948
5949 /* Set up appropriate ctrlFlags */
5950 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5951 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00005952 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00005953 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5954 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5955 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5956
drh7ed97b92010-01-20 13:07:21 +00005957#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005958#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005959 isAutoProxy = 1;
5960#endif
5961 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005962 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5963 int useProxy = 0;
5964
dan08da86a2009-08-21 17:18:03 +00005965 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5966 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005967 if( envforce!=NULL ){
5968 useProxy = atoi(envforce)>0;
5969 }else{
aswiftaebf4132008-11-21 00:10:35 +00005970 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5971 }
5972 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005973 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005974 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005975 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005976 if( rc!=SQLITE_OK ){
5977 /* Use unixClose to clean up the resources added in fillInUnixFile
5978 ** and clear all the structure's references. Specifically,
5979 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5980 */
5981 unixClose(pFile);
5982 return rc;
5983 }
aswiftaebf4132008-11-21 00:10:35 +00005984 }
dane946c392009-08-22 11:39:46 +00005985 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005986 }
5987 }
5988#endif
5989
dan3ed0f1c2017-09-14 21:12:07 +00005990 assert( zPath==0 || zPath[0]=='/'
5991 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
5992 );
drhc02a43a2012-01-10 23:18:38 +00005993 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5994
dane946c392009-08-22 11:39:46 +00005995open_finished:
5996 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00005997 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00005998 }
5999 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006000}
6001
dane946c392009-08-22 11:39:46 +00006002
danielk1977b4b47412007-08-17 15:53:36 +00006003/*
danielk1977fee2d252007-08-18 10:59:19 +00006004** Delete the file at zPath. If the dirSync argument is true, fsync()
6005** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006006*/
drh6b9d6dd2008-12-03 19:34:47 +00006007static int unixDelete(
6008 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6009 const char *zPath, /* Name of file to be deleted */
6010 int dirSync /* If true, fsync() directory after deleting file */
6011){
danielk1977fee2d252007-08-18 10:59:19 +00006012 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006013 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006014 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006015 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006016 if( errno==ENOENT
6017#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006018 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006019#endif
6020 ){
dan9fc5b4a2012-11-09 20:17:26 +00006021 rc = SQLITE_IOERR_DELETE_NOENT;
6022 }else{
drhb4308162012-11-09 21:40:02 +00006023 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006024 }
drhb4308162012-11-09 21:40:02 +00006025 return rc;
drh5d4feff2010-07-14 01:45:22 +00006026 }
danielk1977d39fa702008-10-16 13:27:40 +00006027#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006028 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006029 int fd;
drh90315a22011-08-10 01:52:12 +00006030 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006031 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006032 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006033 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006034 }
drh0e9365c2011-03-02 02:08:13 +00006035 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006036 }else{
6037 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006038 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006039 }
6040 }
danielk1977d138dd82008-10-15 16:02:48 +00006041#endif
danielk1977fee2d252007-08-18 10:59:19 +00006042 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006043}
6044
danielk197790949c22007-08-17 16:50:38 +00006045/*
mistachkin48864df2013-03-21 21:20:32 +00006046** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006047** test performed depends on the value of flags:
6048**
6049** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6050** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6051** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6052**
6053** Otherwise return 0.
6054*/
danielk1977861f7452008-06-05 11:39:11 +00006055static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006056 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6057 const char *zPath, /* Path of the file to examine */
6058 int flags, /* What do we want to learn about the zPath file? */
6059 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006060){
danielk1977397d65f2008-11-19 11:35:39 +00006061 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006062 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006063 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006064
drhd260b5b2015-11-25 18:03:33 +00006065 /* The spec says there are three possible values for flags. But only
6066 ** two of them are actually used */
6067 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6068
6069 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006070 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006071 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6072 }else{
6073 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006074 }
danielk1977861f7452008-06-05 11:39:11 +00006075 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006076}
6077
danielk1977b4b47412007-08-17 15:53:36 +00006078/*
danielk1977b4b47412007-08-17 15:53:36 +00006079**
danielk1977b4b47412007-08-17 15:53:36 +00006080*/
dane88ec182016-01-25 17:04:48 +00006081static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006082 const char *zPath, /* Input path */
6083 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006084 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006085){
dancaf6b152016-01-25 18:05:49 +00006086 int nPath = sqlite3Strlen30(zPath);
6087 int iOff = 0;
6088 if( zPath[0]!='/' ){
6089 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006090 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006091 }
dancaf6b152016-01-25 18:05:49 +00006092 iOff = sqlite3Strlen30(zOut);
6093 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006094 }
dan23496702016-01-26 13:56:42 +00006095 if( (iOff+nPath+1)>nOut ){
6096 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6097 ** even if it returns an error. */
6098 zOut[iOff] = '\0';
6099 return SQLITE_CANTOPEN_BKPT;
6100 }
dancaf6b152016-01-25 18:05:49 +00006101 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006102 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006103}
6104
dane88ec182016-01-25 17:04:48 +00006105/*
6106** Turn a relative pathname into a full pathname. The relative path
6107** is stored as a nul-terminated string in the buffer pointed to by
6108** zPath.
6109**
6110** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6111** (in this case, MAX_PATHNAME bytes). The full-path is written to
6112** this buffer before returning.
6113*/
6114static int unixFullPathname(
6115 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6116 const char *zPath, /* Possibly relative input path */
6117 int nOut, /* Size of output buffer in bytes */
6118 char *zOut /* Output buffer */
6119){
danaf1b36b2016-01-25 18:43:05 +00006120#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006121 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006122#else
6123 int rc = SQLITE_OK;
6124 int nByte;
dancaf6b152016-01-25 18:05:49 +00006125 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006126 const char *zIn = zPath; /* Input path for each iteration of loop */
6127 char *zDel = 0;
6128
6129 assert( pVfs->mxPathname==MAX_PATHNAME );
6130 UNUSED_PARAMETER(pVfs);
6131
6132 /* It's odd to simulate an io-error here, but really this is just
6133 ** using the io-error infrastructure to test that SQLite handles this
6134 ** function failing. This function could fail if, for example, the
6135 ** current working directory has been unlinked.
6136 */
6137 SimulateIOError( return SQLITE_ERROR );
6138
6139 do {
6140
dancaf6b152016-01-25 18:05:49 +00006141 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6142 ** link, or false otherwise. */
6143 int bLink = 0;
6144 struct stat buf;
6145 if( osLstat(zIn, &buf)!=0 ){
6146 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006147 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006148 }
dane88ec182016-01-25 17:04:48 +00006149 }else{
dancaf6b152016-01-25 18:05:49 +00006150 bLink = S_ISLNK(buf.st_mode);
6151 }
6152
6153 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006154 if( zDel==0 ){
6155 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006156 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006157 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6158 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006159 }
dancaf6b152016-01-25 18:05:49 +00006160
6161 if( rc==SQLITE_OK ){
6162 nByte = osReadlink(zIn, zDel, nOut-1);
6163 if( nByte<0 ){
6164 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006165 }else{
6166 if( zDel[0]!='/' ){
6167 int n;
6168 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6169 if( nByte+n+1>nOut ){
6170 rc = SQLITE_CANTOPEN_BKPT;
6171 }else{
6172 memmove(&zDel[n], zDel, nByte+1);
6173 memcpy(zDel, zIn, n);
6174 nByte += n;
6175 }
dancaf6b152016-01-25 18:05:49 +00006176 }
6177 zDel[nByte] = '\0';
6178 }
6179 }
6180
6181 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006182 }
6183
dan23496702016-01-26 13:56:42 +00006184 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6185 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006186 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006187 }
dancaf6b152016-01-25 18:05:49 +00006188 if( bLink==0 ) break;
6189 zIn = zOut;
6190 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006191
6192 sqlite3_free(zDel);
6193 return rc;
danaf1b36b2016-01-25 18:43:05 +00006194#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006195}
6196
drh0ccebe72005-06-07 22:22:50 +00006197
drh761df872006-12-21 01:29:22 +00006198#ifndef SQLITE_OMIT_LOAD_EXTENSION
6199/*
6200** Interfaces for opening a shared library, finding entry points
6201** within the shared library, and closing the shared library.
6202*/
6203#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006204static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6205 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006206 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6207}
danielk197795c8a542007-09-01 06:51:27 +00006208
6209/*
6210** SQLite calls this function immediately after a call to unixDlSym() or
6211** unixDlOpen() fails (returns a null pointer). If a more detailed error
6212** message is available, it is written to zBufOut. If no error message
6213** is available, zBufOut is left unmodified and SQLite uses a default
6214** error message.
6215*/
danielk1977397d65f2008-11-19 11:35:39 +00006216static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006217 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006218 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006219 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006220 zErr = dlerror();
6221 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006222 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006223 }
drh6c7d5c52008-11-21 20:32:33 +00006224 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006225}
drh1875f7a2008-12-08 18:19:17 +00006226static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6227 /*
6228 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6229 ** cast into a pointer to a function. And yet the library dlsym() routine
6230 ** returns a void* which is really a pointer to a function. So how do we
6231 ** use dlsym() with -pedantic-errors?
6232 **
6233 ** Variable x below is defined to be a pointer to a function taking
6234 ** parameters void* and const char* and returning a pointer to a function.
6235 ** We initialize x by assigning it a pointer to the dlsym() function.
6236 ** (That assignment requires a cast.) Then we call the function that
6237 ** x points to.
6238 **
6239 ** This work-around is unlikely to work correctly on any system where
6240 ** you really cannot cast a function pointer into void*. But then, on the
6241 ** other hand, dlsym() will not work on such a system either, so we have
6242 ** not really lost anything.
6243 */
6244 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006245 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006246 x = (void(*(*)(void*,const char*))(void))dlsym;
6247 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006248}
danielk1977397d65f2008-11-19 11:35:39 +00006249static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6250 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006251 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006252}
danielk1977b4b47412007-08-17 15:53:36 +00006253#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6254 #define unixDlOpen 0
6255 #define unixDlError 0
6256 #define unixDlSym 0
6257 #define unixDlClose 0
6258#endif
6259
6260/*
danielk197790949c22007-08-17 16:50:38 +00006261** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006262*/
danielk1977397d65f2008-11-19 11:35:39 +00006263static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6264 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006265 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006266
drhbbd42a62004-05-22 17:41:58 +00006267 /* We have to initialize zBuf to prevent valgrind from reporting
6268 ** errors. The reports issued by valgrind are incorrect - we would
6269 ** prefer that the randomness be increased by making use of the
6270 ** uninitialized space in zBuf - but valgrind errors tend to worry
6271 ** some users. Rather than argue, it seems easier just to initialize
6272 ** the whole array and silence valgrind, even if that means less randomness
6273 ** in the random seed.
6274 **
6275 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006276 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006277 ** tests repeatable.
6278 */
danielk1977b4b47412007-08-17 15:53:36 +00006279 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006280 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006281#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006282 {
drhb00d8622014-01-01 15:18:36 +00006283 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006284 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006285 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006286 time_t t;
6287 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006288 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006289 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6290 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6291 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006292 }else{
drhc18b4042012-02-10 03:10:27 +00006293 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006294 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006295 }
drhbbd42a62004-05-22 17:41:58 +00006296 }
6297#endif
drh72cbd072008-10-14 17:58:38 +00006298 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006299}
6300
danielk1977b4b47412007-08-17 15:53:36 +00006301
drhbbd42a62004-05-22 17:41:58 +00006302/*
6303** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006304** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006305** The return value is the number of microseconds of sleep actually
6306** requested from the underlying operating system, a number which
6307** might be greater than or equal to the argument, but not less
6308** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006309*/
danielk1977397d65f2008-11-19 11:35:39 +00006310static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006311#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006312 struct timespec sp;
6313
6314 sp.tv_sec = microseconds / 1000000;
6315 sp.tv_nsec = (microseconds % 1000000) * 1000;
6316 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006317 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006318 return microseconds;
6319#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006320 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006321 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006322 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006323#else
danielk1977b4b47412007-08-17 15:53:36 +00006324 int seconds = (microseconds+999999)/1000000;
6325 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006326 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006327 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006328#endif
drh88f474a2006-01-02 20:00:12 +00006329}
6330
6331/*
drh6b9d6dd2008-12-03 19:34:47 +00006332** The following variable, if set to a non-zero value, is interpreted as
6333** the number of seconds since 1970 and is used to set the result of
6334** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006335*/
6336#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006337int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006338#endif
6339
6340/*
drhb7e8ea22010-05-03 14:32:30 +00006341** Find the current time (in Universal Coordinated Time). Write into *piNow
6342** the current time and date as a Julian Day number times 86_400_000. In
6343** other words, write into *piNow the number of milliseconds since the Julian
6344** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6345** proleptic Gregorian calendar.
6346**
drh31702252011-10-12 23:13:43 +00006347** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6348** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006349*/
6350static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6351 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006352 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006353#if defined(NO_GETTOD)
6354 time_t t;
6355 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006356 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006357#elif OS_VXWORKS
6358 struct timespec sNow;
6359 clock_gettime(CLOCK_REALTIME, &sNow);
6360 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6361#else
6362 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006363 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6364 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006365#endif
6366
6367#ifdef SQLITE_TEST
6368 if( sqlite3_current_time ){
6369 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6370 }
6371#endif
6372 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006373 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006374}
6375
drhc3dfa5e2016-01-22 19:44:03 +00006376#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006377/*
drhbbd42a62004-05-22 17:41:58 +00006378** Find the current time (in Universal Coordinated Time). Write the
6379** current time and date as a Julian Day number into *prNow and
6380** return 0. Return 1 if the time and date cannot be found.
6381*/
danielk1977397d65f2008-11-19 11:35:39 +00006382static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006383 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006384 int rc;
drhff828942010-06-26 21:34:06 +00006385 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006386 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006387 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006388 return rc;
drhbbd42a62004-05-22 17:41:58 +00006389}
drh5337dac2015-11-25 15:15:03 +00006390#else
6391# define unixCurrentTime 0
6392#endif
danielk1977b4b47412007-08-17 15:53:36 +00006393
drh6b9d6dd2008-12-03 19:34:47 +00006394/*
drh1b9f2142016-03-17 16:01:23 +00006395** The xGetLastError() method is designed to return a better
6396** low-level error message when operating-system problems come up
6397** during SQLite operation. Only the integer return code is currently
6398** used.
drh6b9d6dd2008-12-03 19:34:47 +00006399*/
danielk1977397d65f2008-11-19 11:35:39 +00006400static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6401 UNUSED_PARAMETER(NotUsed);
6402 UNUSED_PARAMETER(NotUsed2);
6403 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006404 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006405}
6406
drhf2424c52010-04-26 00:04:55 +00006407
6408/*
drh734c9862008-11-28 15:37:20 +00006409************************ End of sqlite3_vfs methods ***************************
6410******************************************************************************/
6411
drh715ff302008-12-03 22:32:44 +00006412/******************************************************************************
6413************************** Begin Proxy Locking ********************************
6414**
6415** Proxy locking is a "uber-locking-method" in this sense: It uses the
6416** other locking methods on secondary lock files. Proxy locking is a
6417** meta-layer over top of the primitive locking implemented above. For
6418** this reason, the division that implements of proxy locking is deferred
6419** until late in the file (here) after all of the other I/O methods have
6420** been defined - so that the primitive locking methods are available
6421** as services to help with the implementation of proxy locking.
6422**
6423****
6424**
6425** The default locking schemes in SQLite use byte-range locks on the
6426** database file to coordinate safe, concurrent access by multiple readers
6427** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6428** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6429** as POSIX read & write locks over fixed set of locations (via fsctl),
6430** on AFP and SMB only exclusive byte-range locks are available via fsctl
6431** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6432** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6433** address in the shared range is taken for a SHARED lock, the entire
6434** shared range is taken for an EXCLUSIVE lock):
6435**
drhf2f105d2012-08-20 15:53:54 +00006436** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006437** RESERVED_BYTE 0x40000001
6438** SHARED_RANGE 0x40000002 -> 0x40000200
6439**
6440** This works well on the local file system, but shows a nearly 100x
6441** slowdown in read performance on AFP because the AFP client disables
6442** the read cache when byte-range locks are present. Enabling the read
6443** cache exposes a cache coherency problem that is present on all OS X
6444** supported network file systems. NFS and AFP both observe the
6445** close-to-open semantics for ensuring cache coherency
6446** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6447** address the requirements for concurrent database access by multiple
6448** readers and writers
6449** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6450**
6451** To address the performance and cache coherency issues, proxy file locking
6452** changes the way database access is controlled by limiting access to a
6453** single host at a time and moving file locks off of the database file
6454** and onto a proxy file on the local file system.
6455**
6456**
6457** Using proxy locks
6458** -----------------
6459**
6460** C APIs
6461**
drh4bf66fd2015-02-19 02:43:02 +00006462** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006463** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006464** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6465** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006466**
6467**
6468** SQL pragmas
6469**
6470** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6471** PRAGMA [database.]lock_proxy_file
6472**
6473** Specifying ":auto:" means that if there is a conch file with a matching
6474** host ID in it, the proxy path in the conch file will be used, otherwise
6475** a proxy path based on the user's temp dir
6476** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6477** actual proxy file name is generated from the name and path of the
6478** database file. For example:
6479**
6480** For database path "/Users/me/foo.db"
6481** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6482**
6483** Once a lock proxy is configured for a database connection, it can not
6484** be removed, however it may be switched to a different proxy path via
6485** the above APIs (assuming the conch file is not being held by another
6486** connection or process).
6487**
6488**
6489** How proxy locking works
6490** -----------------------
6491**
6492** Proxy file locking relies primarily on two new supporting files:
6493**
6494** * conch file to limit access to the database file to a single host
6495** at a time
6496**
6497** * proxy file to act as a proxy for the advisory locks normally
6498** taken on the database
6499**
6500** The conch file - to use a proxy file, sqlite must first "hold the conch"
6501** by taking an sqlite-style shared lock on the conch file, reading the
6502** contents and comparing the host's unique host ID (see below) and lock
6503** proxy path against the values stored in the conch. The conch file is
6504** stored in the same directory as the database file and the file name
6505** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006506** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006507** host ID and/or proxy path, then the lock is escalated to an exclusive
6508** lock and the conch file contents is updated with the host ID and proxy
6509** path and the lock is downgraded to a shared lock again. If the conch
6510** is held by another process (with a shared lock), the exclusive lock
6511** will fail and SQLITE_BUSY is returned.
6512**
6513** The proxy file - a single-byte file used for all advisory file locks
6514** normally taken on the database file. This allows for safe sharing
6515** of the database file for multiple readers and writers on the same
6516** host (the conch ensures that they all use the same local lock file).
6517**
drh715ff302008-12-03 22:32:44 +00006518** Requesting the lock proxy does not immediately take the conch, it is
6519** only taken when the first request to lock database file is made.
6520** This matches the semantics of the traditional locking behavior, where
6521** opening a connection to a database file does not take a lock on it.
6522** The shared lock and an open file descriptor are maintained until
6523** the connection to the database is closed.
6524**
6525** The proxy file and the lock file are never deleted so they only need
6526** to be created the first time they are used.
6527**
6528** Configuration options
6529** ---------------------
6530**
6531** SQLITE_PREFER_PROXY_LOCKING
6532**
6533** Database files accessed on non-local file systems are
6534** automatically configured for proxy locking, lock files are
6535** named automatically using the same logic as
6536** PRAGMA lock_proxy_file=":auto:"
6537**
6538** SQLITE_PROXY_DEBUG
6539**
6540** Enables the logging of error messages during host id file
6541** retrieval and creation
6542**
drh715ff302008-12-03 22:32:44 +00006543** LOCKPROXYDIR
6544**
6545** Overrides the default directory used for lock proxy files that
6546** are named automatically via the ":auto:" setting
6547**
6548** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6549**
6550** Permissions to use when creating a directory for storing the
6551** lock proxy files, only used when LOCKPROXYDIR is not set.
6552**
6553**
6554** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6555** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6556** force proxy locking to be used for every database file opened, and 0
6557** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006558** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006559** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6560*/
6561
6562/*
6563** Proxy locking is only available on MacOSX
6564*/
drhd2cb50b2009-01-09 21:41:17 +00006565#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006566
drh715ff302008-12-03 22:32:44 +00006567/*
6568** The proxyLockingContext has the path and file structures for the remote
6569** and local proxy files in it
6570*/
6571typedef struct proxyLockingContext proxyLockingContext;
6572struct proxyLockingContext {
6573 unixFile *conchFile; /* Open conch file */
6574 char *conchFilePath; /* Name of the conch file */
6575 unixFile *lockProxy; /* Open proxy lock file */
6576 char *lockProxyPath; /* Name of the proxy lock file */
6577 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006578 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006579 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006580 void *oldLockingContext; /* Original lockingcontext to restore on close */
6581 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6582};
6583
drh7ed97b92010-01-20 13:07:21 +00006584/*
6585** The proxy lock file path for the database at dbPath is written into lPath,
6586** which must point to valid, writable memory large enough for a maxLen length
6587** file path.
drh715ff302008-12-03 22:32:44 +00006588*/
drh715ff302008-12-03 22:32:44 +00006589static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6590 int len;
6591 int dbLen;
6592 int i;
6593
6594#ifdef LOCKPROXYDIR
6595 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6596#else
6597# ifdef _CS_DARWIN_USER_TEMP_DIR
6598 {
drh7ed97b92010-01-20 13:07:21 +00006599 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006600 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006601 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006602 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006603 }
drh7ed97b92010-01-20 13:07:21 +00006604 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006605 }
6606# else
6607 len = strlcpy(lPath, "/tmp/", maxLen);
6608# endif
6609#endif
6610
6611 if( lPath[len-1]!='/' ){
6612 len = strlcat(lPath, "/", maxLen);
6613 }
6614
6615 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006616 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006617 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006618 char c = dbPath[i];
6619 lPath[i+len] = (c=='/')?'_':c;
6620 }
6621 lPath[i+len]='\0';
6622 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006623 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006624 return SQLITE_OK;
6625}
6626
drh7ed97b92010-01-20 13:07:21 +00006627/*
6628 ** Creates the lock file and any missing directories in lockPath
6629 */
6630static int proxyCreateLockPath(const char *lockPath){
6631 int i, len;
6632 char buf[MAXPATHLEN];
6633 int start = 0;
6634
6635 assert(lockPath!=NULL);
6636 /* try to create all the intermediate directories */
6637 len = (int)strlen(lockPath);
6638 buf[0] = lockPath[0];
6639 for( i=1; i<len; i++ ){
6640 if( lockPath[i] == '/' && (i - start > 0) ){
6641 /* only mkdir if leaf dir != "." or "/" or ".." */
6642 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6643 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6644 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006645 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006646 int err=errno;
6647 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006648 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006649 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006650 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006651 return err;
6652 }
6653 }
6654 }
6655 start=i+1;
6656 }
6657 buf[i] = lockPath[i];
6658 }
drh62aaa6c2015-11-21 17:27:42 +00006659 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006660 return 0;
6661}
6662
drh715ff302008-12-03 22:32:44 +00006663/*
6664** Create a new VFS file descriptor (stored in memory obtained from
6665** sqlite3_malloc) and open the file named "path" in the file descriptor.
6666**
6667** The caller is responsible not only for closing the file descriptor
6668** but also for freeing the memory associated with the file descriptor.
6669*/
drh7ed97b92010-01-20 13:07:21 +00006670static int proxyCreateUnixFile(
6671 const char *path, /* path for the new unixFile */
6672 unixFile **ppFile, /* unixFile created and returned by ref */
6673 int islockfile /* if non zero missing dirs will be created */
6674) {
6675 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006676 unixFile *pNew;
6677 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006678 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006679 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006680 int terrno = 0;
6681 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006682
drh7ed97b92010-01-20 13:07:21 +00006683 /* 1. first try to open/create the file
6684 ** 2. if that fails, and this is a lock file (not-conch), try creating
6685 ** the parent directories and then try again.
6686 ** 3. if that fails, try to open the file read-only
6687 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6688 */
6689 pUnused = findReusableFd(path, openFlags);
6690 if( pUnused ){
6691 fd = pUnused->fd;
6692 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006693 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006694 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006695 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006696 }
6697 }
6698 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006699 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006700 terrno = errno;
6701 if( fd<0 && errno==ENOENT && islockfile ){
6702 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006703 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006704 }
6705 }
6706 }
6707 if( fd<0 ){
6708 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006709 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006710 terrno = errno;
6711 }
6712 if( fd<0 ){
6713 if( islockfile ){
6714 return SQLITE_BUSY;
6715 }
6716 switch (terrno) {
6717 case EACCES:
6718 return SQLITE_PERM;
6719 case EIO:
6720 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6721 default:
drh9978c972010-02-23 17:36:32 +00006722 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006723 }
6724 }
6725
drhf3cdcdc2015-04-29 16:50:28 +00006726 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006727 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006728 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006729 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006730 }
6731 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006732 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006733 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006734 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006735 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006736 pUnused->fd = fd;
6737 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006738 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006739
drhc02a43a2012-01-10 23:18:38 +00006740 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006741 if( rc==SQLITE_OK ){
6742 *ppFile = pNew;
6743 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006744 }
drh7ed97b92010-01-20 13:07:21 +00006745end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006746 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006747 sqlite3_free(pNew);
6748 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006749 return rc;
6750}
6751
drh7ed97b92010-01-20 13:07:21 +00006752#ifdef SQLITE_TEST
6753/* simulate multiple hosts by creating unique hostid file paths */
6754int sqlite3_hostid_num = 0;
6755#endif
6756
6757#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6758
drh6bca6512015-04-13 23:05:28 +00006759#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006760/* Not always defined in the headers as it ought to be */
6761extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006762#endif
drh0ab216a2010-07-02 17:10:40 +00006763
drh7ed97b92010-01-20 13:07:21 +00006764/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6765** bytes of writable memory.
6766*/
6767static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006768 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6769 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006770#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006771 {
drh4bf66fd2015-02-19 02:43:02 +00006772 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006773 if( gethostuuid(pHostID, &timeout) ){
6774 int err = errno;
6775 if( pError ){
6776 *pError = err;
6777 }
6778 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006779 }
drh7ed97b92010-01-20 13:07:21 +00006780 }
drh3d4435b2011-08-26 20:55:50 +00006781#else
6782 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006783#endif
drh7ed97b92010-01-20 13:07:21 +00006784#ifdef SQLITE_TEST
6785 /* simulate multiple hosts by creating unique hostid file paths */
6786 if( sqlite3_hostid_num != 0){
6787 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6788 }
6789#endif
6790
6791 return SQLITE_OK;
6792}
6793
6794/* The conch file contains the header, host id and lock file path
6795 */
6796#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6797#define PROXY_HEADERLEN 1 /* conch file header length */
6798#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6799#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6800
6801/*
6802** Takes an open conch file, copies the contents to a new path and then moves
6803** it back. The newly created file's file descriptor is assigned to the
6804** conch file structure and finally the original conch file descriptor is
6805** closed. Returns zero if successful.
6806*/
6807static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6808 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6809 unixFile *conchFile = pCtx->conchFile;
6810 char tPath[MAXPATHLEN];
6811 char buf[PROXY_MAXCONCHLEN];
6812 char *cPath = pCtx->conchFilePath;
6813 size_t readLen = 0;
6814 size_t pathLen = 0;
6815 char errmsg[64] = "";
6816 int fd = -1;
6817 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006818 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006819
6820 /* create a new path by replace the trailing '-conch' with '-break' */
6821 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6822 if( pathLen>MAXPATHLEN || pathLen<6 ||
6823 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006824 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006825 goto end_breaklock;
6826 }
6827 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006828 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006829 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006830 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006831 goto end_breaklock;
6832 }
6833 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006834 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006835 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006836 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006837 goto end_breaklock;
6838 }
drhe562be52011-03-02 18:01:10 +00006839 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006840 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006841 goto end_breaklock;
6842 }
6843 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006844 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006845 goto end_breaklock;
6846 }
6847 rc = 0;
6848 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006849 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006850 conchFile->h = fd;
6851 conchFile->openFlags = O_RDWR | O_CREAT;
6852
6853end_breaklock:
6854 if( rc ){
6855 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006856 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006857 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006858 }
6859 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6860 }
6861 return rc;
6862}
6863
6864/* Take the requested lock on the conch file and break a stale lock if the
6865** host id matches.
6866*/
6867static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6868 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6869 unixFile *conchFile = pCtx->conchFile;
6870 int rc = SQLITE_OK;
6871 int nTries = 0;
6872 struct timespec conchModTime;
6873
drh3d4435b2011-08-26 20:55:50 +00006874 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006875 do {
6876 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6877 nTries ++;
6878 if( rc==SQLITE_BUSY ){
6879 /* If the lock failed (busy):
6880 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6881 * 2nd try: fail if the mod time changed or host id is different, wait
6882 * 10 sec and try again
6883 * 3rd try: break the lock unless the mod time has changed.
6884 */
6885 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006886 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006887 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006888 return SQLITE_IOERR_LOCK;
6889 }
6890
6891 if( nTries==1 ){
6892 conchModTime = buf.st_mtimespec;
6893 usleep(500000); /* wait 0.5 sec and try the lock again*/
6894 continue;
6895 }
6896
6897 assert( nTries>1 );
6898 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6899 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6900 return SQLITE_BUSY;
6901 }
6902
6903 if( nTries==2 ){
6904 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006905 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006906 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006907 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006908 return SQLITE_IOERR_LOCK;
6909 }
6910 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6911 /* don't break the lock if the host id doesn't match */
6912 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6913 return SQLITE_BUSY;
6914 }
6915 }else{
6916 /* don't break the lock on short read or a version mismatch */
6917 return SQLITE_BUSY;
6918 }
6919 usleep(10000000); /* wait 10 sec and try the lock again */
6920 continue;
6921 }
6922
6923 assert( nTries==3 );
6924 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6925 rc = SQLITE_OK;
6926 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006927 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006928 }
6929 if( !rc ){
6930 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6931 }
6932 }
6933 }
6934 } while( rc==SQLITE_BUSY && nTries<3 );
6935
6936 return rc;
6937}
6938
6939/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006940** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6941** lockPath means that the lockPath in the conch file will be used if the
6942** host IDs match, or a new lock path will be generated automatically
6943** and written to the conch file.
6944*/
6945static int proxyTakeConch(unixFile *pFile){
6946 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6947
drh7ed97b92010-01-20 13:07:21 +00006948 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006949 return SQLITE_OK;
6950 }else{
6951 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006952 uuid_t myHostID;
6953 int pError = 0;
6954 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006955 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006956 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006957 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006958 int createConch = 0;
6959 int hostIdMatch = 0;
6960 int readLen = 0;
6961 int tryOldLockPath = 0;
6962 int forceNewLockPath = 0;
6963
drh308c2a52010-05-14 11:30:18 +00006964 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006965 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006966 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006967
drh7ed97b92010-01-20 13:07:21 +00006968 rc = proxyGetHostID(myHostID, &pError);
6969 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006970 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006971 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006972 }
drh7ed97b92010-01-20 13:07:21 +00006973 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006974 if( rc!=SQLITE_OK ){
6975 goto end_takeconch;
6976 }
drh7ed97b92010-01-20 13:07:21 +00006977 /* read the existing conch file */
6978 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6979 if( readLen<0 ){
6980 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006981 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006982 rc = SQLITE_IOERR_READ;
6983 goto end_takeconch;
6984 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6985 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6986 /* a short read or version format mismatch means we need to create a new
6987 ** conch file.
6988 */
6989 createConch = 1;
6990 }
6991 /* if the host id matches and the lock path already exists in the conch
6992 ** we'll try to use the path there, if we can't open that path, we'll
6993 ** retry with a new auto-generated path
6994 */
6995 do { /* in case we need to try again for an :auto: named lock file */
6996
6997 if( !createConch && !forceNewLockPath ){
6998 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6999 PROXY_HOSTIDLEN);
7000 /* if the conch has data compare the contents */
7001 if( !pCtx->lockProxyPath ){
7002 /* for auto-named local lock file, just check the host ID and we'll
7003 ** use the local lock file path that's already in there
7004 */
7005 if( hostIdMatch ){
7006 size_t pathLen = (readLen - PROXY_PATHINDEX);
7007
7008 if( pathLen>=MAXPATHLEN ){
7009 pathLen=MAXPATHLEN-1;
7010 }
7011 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7012 lockPath[pathLen] = 0;
7013 tempLockPath = lockPath;
7014 tryOldLockPath = 1;
7015 /* create a copy of the lock path if the conch is taken */
7016 goto end_takeconch;
7017 }
7018 }else if( hostIdMatch
7019 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7020 readLen-PROXY_PATHINDEX)
7021 ){
7022 /* conch host and lock path match */
7023 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007024 }
drh7ed97b92010-01-20 13:07:21 +00007025 }
7026
7027 /* if the conch isn't writable and doesn't match, we can't take it */
7028 if( (conchFile->openFlags&O_RDWR) == 0 ){
7029 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007030 goto end_takeconch;
7031 }
drh7ed97b92010-01-20 13:07:21 +00007032
7033 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007034 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007035 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7036 tempLockPath = lockPath;
7037 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007038 }
drh7ed97b92010-01-20 13:07:21 +00007039
7040 /* update conch with host and path (this will fail if other process
7041 ** has a shared lock already), if the host id matches, use the big
7042 ** stick.
drh715ff302008-12-03 22:32:44 +00007043 */
drh7ed97b92010-01-20 13:07:21 +00007044 futimes(conchFile->h, NULL);
7045 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007046 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007047 /* We are trying for an exclusive lock but another thread in this
7048 ** same process is still holding a shared lock. */
7049 rc = SQLITE_BUSY;
7050 } else {
7051 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007052 }
drh715ff302008-12-03 22:32:44 +00007053 }else{
drh4bf66fd2015-02-19 02:43:02 +00007054 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007055 }
drh7ed97b92010-01-20 13:07:21 +00007056 if( rc==SQLITE_OK ){
7057 char writeBuffer[PROXY_MAXCONCHLEN];
7058 int writeSize = 0;
7059
7060 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7061 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7062 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007063 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7064 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007065 }else{
7066 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7067 }
7068 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007069 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007070 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007071 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007072 /* If we created a new conch file (not just updated the contents of a
7073 ** valid conch file), try to match the permissions of the database
7074 */
7075 if( rc==SQLITE_OK && createConch ){
7076 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007077 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007078 if( err==0 ){
7079 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7080 S_IROTH|S_IWOTH);
7081 /* try to match the database file R/W permissions, ignore failure */
7082#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007083 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007084#else
drhff812312011-02-23 13:33:46 +00007085 do{
drhe562be52011-03-02 18:01:10 +00007086 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007087 }while( rc==(-1) && errno==EINTR );
7088 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007089 int code = errno;
7090 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7091 cmode, code, strerror(code));
7092 } else {
7093 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7094 }
7095 }else{
7096 int code = errno;
7097 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7098 err, code, strerror(code));
7099#endif
7100 }
drh715ff302008-12-03 22:32:44 +00007101 }
7102 }
drh7ed97b92010-01-20 13:07:21 +00007103 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7104
7105 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007106 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007107 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007108 int fd;
drh7ed97b92010-01-20 13:07:21 +00007109 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007110 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007111 }
7112 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007113 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007114 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007115 if( fd>=0 ){
7116 pFile->h = fd;
7117 }else{
drh9978c972010-02-23 17:36:32 +00007118 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007119 during locking */
7120 }
7121 }
7122 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7123 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7124 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7125 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7126 /* we couldn't create the proxy lock file with the old lock file path
7127 ** so try again via auto-naming
7128 */
7129 forceNewLockPath = 1;
7130 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007131 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007132 }
7133 }
7134 if( rc==SQLITE_OK ){
7135 /* Need to make a copy of path if we extracted the value
7136 ** from the conch file or the path was allocated on the stack
7137 */
7138 if( tempLockPath ){
7139 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7140 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007141 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007142 }
7143 }
7144 }
7145 if( rc==SQLITE_OK ){
7146 pCtx->conchHeld = 1;
7147
7148 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7149 afpLockingContext *afpCtx;
7150 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7151 afpCtx->dbPath = pCtx->lockProxyPath;
7152 }
7153 } else {
7154 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7155 }
drh308c2a52010-05-14 11:30:18 +00007156 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7157 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007158 return rc;
drh308c2a52010-05-14 11:30:18 +00007159 } while (1); /* in case we need to retry the :auto: lock file -
7160 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007161 }
7162}
7163
7164/*
7165** If pFile holds a lock on a conch file, then release that lock.
7166*/
7167static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007168 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007169 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7170 unixFile *conchFile; /* Name of the conch file */
7171
7172 pCtx = (proxyLockingContext *)pFile->lockingContext;
7173 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007174 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007175 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007176 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007177 if( pCtx->conchHeld>0 ){
7178 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7179 }
drh715ff302008-12-03 22:32:44 +00007180 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007181 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7182 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007183 return rc;
7184}
7185
7186/*
7187** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007188** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007189** Make *pConchPath point to the new name. Return SQLITE_OK on success
7190** or SQLITE_NOMEM if unable to obtain memory.
7191**
7192** The caller is responsible for ensuring that the allocated memory
7193** space is eventually freed.
7194**
7195** *pConchPath is set to NULL if a memory allocation error occurs.
7196*/
7197static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7198 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007199 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007200 char *conchPath; /* buffer in which to construct conch name */
7201
7202 /* Allocate space for the conch filename and initialize the name to
7203 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007204 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007205 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007206 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007207 }
7208 memcpy(conchPath, dbPath, len+1);
7209
7210 /* now insert a "." before the last / character */
7211 for( i=(len-1); i>=0; i-- ){
7212 if( conchPath[i]=='/' ){
7213 i++;
7214 break;
7215 }
7216 }
7217 conchPath[i]='.';
7218 while ( i<len ){
7219 conchPath[i+1]=dbPath[i];
7220 i++;
7221 }
7222
7223 /* append the "-conch" suffix to the file */
7224 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007225 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007226
7227 return SQLITE_OK;
7228}
7229
7230
7231/* Takes a fully configured proxy locking-style unix file and switches
7232** the local lock file path
7233*/
7234static int switchLockProxyPath(unixFile *pFile, const char *path) {
7235 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7236 char *oldPath = pCtx->lockProxyPath;
7237 int rc = SQLITE_OK;
7238
drh308c2a52010-05-14 11:30:18 +00007239 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007240 return SQLITE_BUSY;
7241 }
7242
7243 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7244 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7245 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7246 return SQLITE_OK;
7247 }else{
7248 unixFile *lockProxy = pCtx->lockProxy;
7249 pCtx->lockProxy=NULL;
7250 pCtx->conchHeld = 0;
7251 if( lockProxy!=NULL ){
7252 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7253 if( rc ) return rc;
7254 sqlite3_free(lockProxy);
7255 }
7256 sqlite3_free(oldPath);
7257 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7258 }
7259
7260 return rc;
7261}
7262
7263/*
7264** pFile is a file that has been opened by a prior xOpen call. dbPath
7265** is a string buffer at least MAXPATHLEN+1 characters in size.
7266**
7267** This routine find the filename associated with pFile and writes it
7268** int dbPath.
7269*/
7270static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007271#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007272 if( pFile->pMethod == &afpIoMethods ){
7273 /* afp style keeps a reference to the db path in the filePath field
7274 ** of the struct */
drhea678832008-12-10 19:26:22 +00007275 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007276 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7277 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007278 } else
drh715ff302008-12-03 22:32:44 +00007279#endif
7280 if( pFile->pMethod == &dotlockIoMethods ){
7281 /* dot lock style uses the locking context to store the dot lock
7282 ** file path */
7283 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7284 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7285 }else{
7286 /* all other styles use the locking context to store the db file path */
7287 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007288 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007289 }
7290 return SQLITE_OK;
7291}
7292
7293/*
7294** Takes an already filled in unix file and alters it so all file locking
7295** will be performed on the local proxy lock file. The following fields
7296** are preserved in the locking context so that they can be restored and
7297** the unix structure properly cleaned up at close time:
7298** ->lockingContext
7299** ->pMethod
7300*/
7301static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7302 proxyLockingContext *pCtx;
7303 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7304 char *lockPath=NULL;
7305 int rc = SQLITE_OK;
7306
drh308c2a52010-05-14 11:30:18 +00007307 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007308 return SQLITE_BUSY;
7309 }
7310 proxyGetDbPathForUnixFile(pFile, dbPath);
7311 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7312 lockPath=NULL;
7313 }else{
7314 lockPath=(char *)path;
7315 }
7316
drh308c2a52010-05-14 11:30:18 +00007317 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007318 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007319
drhf3cdcdc2015-04-29 16:50:28 +00007320 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007321 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007322 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007323 }
7324 memset(pCtx, 0, sizeof(*pCtx));
7325
7326 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7327 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007328 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7329 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7330 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7331 ** (c) the file system is read-only, then enable no-locking access.
7332 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7333 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7334 */
7335 struct statfs fsInfo;
7336 struct stat conchInfo;
7337 int goLockless = 0;
7338
drh99ab3b12011-03-02 15:09:07 +00007339 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007340 int err = errno;
7341 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7342 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7343 }
7344 }
7345 if( goLockless ){
7346 pCtx->conchHeld = -1; /* read only FS/ lockless */
7347 rc = SQLITE_OK;
7348 }
7349 }
drh715ff302008-12-03 22:32:44 +00007350 }
7351 if( rc==SQLITE_OK && lockPath ){
7352 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7353 }
7354
7355 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007356 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7357 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007358 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007359 }
7360 }
7361 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007362 /* all memory is allocated, proxys are created and assigned,
7363 ** switch the locking context and pMethod then return.
7364 */
drh715ff302008-12-03 22:32:44 +00007365 pCtx->oldLockingContext = pFile->lockingContext;
7366 pFile->lockingContext = pCtx;
7367 pCtx->pOldMethod = pFile->pMethod;
7368 pFile->pMethod = &proxyIoMethods;
7369 }else{
7370 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007371 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007372 sqlite3_free(pCtx->conchFile);
7373 }
drhd56b1212010-08-11 06:14:15 +00007374 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007375 sqlite3_free(pCtx->conchFilePath);
7376 sqlite3_free(pCtx);
7377 }
drh308c2a52010-05-14 11:30:18 +00007378 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7379 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007380 return rc;
7381}
7382
7383
7384/*
7385** This routine handles sqlite3_file_control() calls that are specific
7386** to proxy locking.
7387*/
7388static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7389 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007390 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007391 unixFile *pFile = (unixFile*)id;
7392 if( pFile->pMethod == &proxyIoMethods ){
7393 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7394 proxyTakeConch(pFile);
7395 if( pCtx->lockProxyPath ){
7396 *(const char **)pArg = pCtx->lockProxyPath;
7397 }else{
7398 *(const char **)pArg = ":auto: (not held)";
7399 }
7400 } else {
7401 *(const char **)pArg = NULL;
7402 }
7403 return SQLITE_OK;
7404 }
drh4bf66fd2015-02-19 02:43:02 +00007405 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007406 unixFile *pFile = (unixFile*)id;
7407 int rc = SQLITE_OK;
7408 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7409 if( pArg==NULL || (const char *)pArg==0 ){
7410 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007411 /* turn off proxy locking - not supported. If support is added for
7412 ** switching proxy locking mode off then it will need to fail if
7413 ** the journal mode is WAL mode.
7414 */
drh715ff302008-12-03 22:32:44 +00007415 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7416 }else{
7417 /* turn off proxy locking - already off - NOOP */
7418 rc = SQLITE_OK;
7419 }
7420 }else{
7421 const char *proxyPath = (const char *)pArg;
7422 if( isProxyStyle ){
7423 proxyLockingContext *pCtx =
7424 (proxyLockingContext*)pFile->lockingContext;
7425 if( !strcmp(pArg, ":auto:")
7426 || (pCtx->lockProxyPath &&
7427 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7428 ){
7429 rc = SQLITE_OK;
7430 }else{
7431 rc = switchLockProxyPath(pFile, proxyPath);
7432 }
7433 }else{
7434 /* turn on proxy file locking */
7435 rc = proxyTransformUnixFile(pFile, proxyPath);
7436 }
7437 }
7438 return rc;
7439 }
7440 default: {
7441 assert( 0 ); /* The call assures that only valid opcodes are sent */
7442 }
7443 }
7444 /*NOTREACHED*/
7445 return SQLITE_ERROR;
7446}
7447
7448/*
7449** Within this division (the proxying locking implementation) the procedures
7450** above this point are all utilities. The lock-related methods of the
7451** proxy-locking sqlite3_io_method object follow.
7452*/
7453
7454
7455/*
7456** This routine checks if there is a RESERVED lock held on the specified
7457** file by this or any other process. If such a lock is held, set *pResOut
7458** to a non-zero value otherwise *pResOut is set to zero. The return value
7459** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7460*/
7461static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7462 unixFile *pFile = (unixFile*)id;
7463 int rc = proxyTakeConch(pFile);
7464 if( rc==SQLITE_OK ){
7465 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007466 if( pCtx->conchHeld>0 ){
7467 unixFile *proxy = pCtx->lockProxy;
7468 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7469 }else{ /* conchHeld < 0 is lockless */
7470 pResOut=0;
7471 }
drh715ff302008-12-03 22:32:44 +00007472 }
7473 return rc;
7474}
7475
7476/*
drh308c2a52010-05-14 11:30:18 +00007477** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007478** of the following:
7479**
7480** (1) SHARED_LOCK
7481** (2) RESERVED_LOCK
7482** (3) PENDING_LOCK
7483** (4) EXCLUSIVE_LOCK
7484**
7485** Sometimes when requesting one lock state, additional lock states
7486** are inserted in between. The locking might fail on one of the later
7487** transitions leaving the lock state different from what it started but
7488** still short of its goal. The following chart shows the allowed
7489** transitions and the inserted intermediate states:
7490**
7491** UNLOCKED -> SHARED
7492** SHARED -> RESERVED
7493** SHARED -> (PENDING) -> EXCLUSIVE
7494** RESERVED -> (PENDING) -> EXCLUSIVE
7495** PENDING -> EXCLUSIVE
7496**
7497** This routine will only increase a lock. Use the sqlite3OsUnlock()
7498** routine to lower a locking level.
7499*/
drh308c2a52010-05-14 11:30:18 +00007500static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007501 unixFile *pFile = (unixFile*)id;
7502 int rc = proxyTakeConch(pFile);
7503 if( rc==SQLITE_OK ){
7504 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007505 if( pCtx->conchHeld>0 ){
7506 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007507 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7508 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007509 }else{
7510 /* conchHeld < 0 is lockless */
7511 }
drh715ff302008-12-03 22:32:44 +00007512 }
7513 return rc;
7514}
7515
7516
7517/*
drh308c2a52010-05-14 11:30:18 +00007518** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007519** must be either NO_LOCK or SHARED_LOCK.
7520**
7521** If the locking level of the file descriptor is already at or below
7522** the requested locking level, this routine is a no-op.
7523*/
drh308c2a52010-05-14 11:30:18 +00007524static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007525 unixFile *pFile = (unixFile*)id;
7526 int rc = proxyTakeConch(pFile);
7527 if( rc==SQLITE_OK ){
7528 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007529 if( pCtx->conchHeld>0 ){
7530 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007531 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7532 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007533 }else{
7534 /* conchHeld < 0 is lockless */
7535 }
drh715ff302008-12-03 22:32:44 +00007536 }
7537 return rc;
7538}
7539
7540/*
7541** Close a file that uses proxy locks.
7542*/
7543static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007544 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007545 unixFile *pFile = (unixFile*)id;
7546 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7547 unixFile *lockProxy = pCtx->lockProxy;
7548 unixFile *conchFile = pCtx->conchFile;
7549 int rc = SQLITE_OK;
7550
7551 if( lockProxy ){
7552 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7553 if( rc ) return rc;
7554 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7555 if( rc ) return rc;
7556 sqlite3_free(lockProxy);
7557 pCtx->lockProxy = 0;
7558 }
7559 if( conchFile ){
7560 if( pCtx->conchHeld ){
7561 rc = proxyReleaseConch(pFile);
7562 if( rc ) return rc;
7563 }
7564 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7565 if( rc ) return rc;
7566 sqlite3_free(conchFile);
7567 }
drhd56b1212010-08-11 06:14:15 +00007568 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007569 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007570 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007571 /* restore the original locking context and pMethod then close it */
7572 pFile->lockingContext = pCtx->oldLockingContext;
7573 pFile->pMethod = pCtx->pOldMethod;
7574 sqlite3_free(pCtx);
7575 return pFile->pMethod->xClose(id);
7576 }
7577 return SQLITE_OK;
7578}
7579
7580
7581
drhd2cb50b2009-01-09 21:41:17 +00007582#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007583/*
7584** The proxy locking style is intended for use with AFP filesystems.
7585** And since AFP is only supported on MacOSX, the proxy locking is also
7586** restricted to MacOSX.
7587**
7588**
7589******************* End of the proxy lock implementation **********************
7590******************************************************************************/
7591
drh734c9862008-11-28 15:37:20 +00007592/*
danielk1977e339d652008-06-28 11:23:00 +00007593** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007594**
7595** This routine registers all VFS implementations for unix-like operating
7596** systems. This routine, and the sqlite3_os_end() routine that follows,
7597** should be the only routines in this file that are visible from other
7598** files.
drh6b9d6dd2008-12-03 19:34:47 +00007599**
7600** This routine is called once during SQLite initialization and by a
7601** single thread. The memory allocation and mutex subsystems have not
7602** necessarily been initialized when this routine is called, and so they
7603** should not be used.
drh153c62c2007-08-24 03:51:33 +00007604*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007605int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007606 /*
7607 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007608 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7609 ** to the "finder" function. (pAppData is a pointer to a pointer because
7610 ** silly C90 rules prohibit a void* from being cast to a function pointer
7611 ** and so we have to go through the intermediate pointer to avoid problems
7612 ** when compiling with -pedantic-errors on GCC.)
7613 **
7614 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007615 ** finder-function. The finder-function returns a pointer to the
7616 ** sqlite_io_methods object that implements the desired locking
7617 ** behaviors. See the division above that contains the IOMETHODS
7618 ** macro for addition information on finder-functions.
7619 **
7620 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7621 ** object. But the "autolockIoFinder" available on MacOSX does a little
7622 ** more than that; it looks at the filesystem type that hosts the
7623 ** database file and tries to choose an locking method appropriate for
7624 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007625 */
drh7708e972008-11-29 00:56:52 +00007626 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007627 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007628 sizeof(unixFile), /* szOsFile */ \
7629 MAX_PATHNAME, /* mxPathname */ \
7630 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007631 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007632 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007633 unixOpen, /* xOpen */ \
7634 unixDelete, /* xDelete */ \
7635 unixAccess, /* xAccess */ \
7636 unixFullPathname, /* xFullPathname */ \
7637 unixDlOpen, /* xDlOpen */ \
7638 unixDlError, /* xDlError */ \
7639 unixDlSym, /* xDlSym */ \
7640 unixDlClose, /* xDlClose */ \
7641 unixRandomness, /* xRandomness */ \
7642 unixSleep, /* xSleep */ \
7643 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007644 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007645 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007646 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007647 unixGetSystemCall, /* xGetSystemCall */ \
7648 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007649 }
7650
drh6b9d6dd2008-12-03 19:34:47 +00007651 /*
7652 ** All default VFSes for unix are contained in the following array.
7653 **
7654 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7655 ** by the SQLite core when the VFS is registered. So the following
7656 ** array cannot be const.
7657 */
danielk1977e339d652008-06-28 11:23:00 +00007658 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007659#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007660 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007661#elif OS_VXWORKS
7662 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007663#else
7664 UNIXVFS("unix", posixIoFinder ),
7665#endif
7666 UNIXVFS("unix-none", nolockIoFinder ),
7667 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007668 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007669#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007670 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007671#endif
drhe89b2912015-03-03 20:42:01 +00007672#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007673 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007674#endif
drhe89b2912015-03-03 20:42:01 +00007675#if SQLITE_ENABLE_LOCKING_STYLE
7676 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007677#endif
drhd2cb50b2009-01-09 21:41:17 +00007678#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007679 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007680 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007681 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007682#endif
drh153c62c2007-08-24 03:51:33 +00007683 };
drh6b9d6dd2008-12-03 19:34:47 +00007684 unsigned int i; /* Loop counter */
7685
drh2aa5a002011-04-13 13:42:25 +00007686 /* Double-check that the aSyscall[] array has been constructed
7687 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007688 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007689
drh6b9d6dd2008-12-03 19:34:47 +00007690 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007691 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007692 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007693 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007694 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007695}
danielk1977e339d652008-06-28 11:23:00 +00007696
7697/*
drh6b9d6dd2008-12-03 19:34:47 +00007698** Shutdown the operating system interface.
7699**
7700** Some operating systems might need to do some cleanup in this routine,
7701** to release dynamically allocated objects. But not on unix.
7702** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007703*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007704int sqlite3_os_end(void){
7705 return SQLITE_OK;
7706}
drhdce8bdb2007-08-16 13:01:44 +00007707
danielk197729bafea2008-06-26 10:41:19 +00007708#endif /* SQLITE_OS_UNIX */