blob: 39519893594311abc6bd46dfb367bec522fcedce [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
danefe16972017-07-20 19:49:14 +0000516 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
dan9d709542017-07-21 21:06:24 +0000517#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
danefe16972017-07-20 19:49:14 +0000518
drhe562be52011-03-02 18:01:10 +0000519}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000520
drh6226ca22015-11-24 15:06:28 +0000521
522/*
523** On some systems, calls to fchown() will trigger a message in a security
524** log if they come from non-root processes. So avoid calling fchown() if
525** we are not running as root.
526*/
527static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000528#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000529 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000530#else
531 return 0;
drh6226ca22015-11-24 15:06:28 +0000532#endif
533}
534
drh99ab3b12011-03-02 15:09:07 +0000535/*
536** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000537** "unix" VFSes. Return SQLITE_OK opon successfully updating the
538** system call pointer, or SQLITE_NOTFOUND if there is no configurable
539** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000540*/
541static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000542 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
543 const char *zName, /* Name of system call to override */
544 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000545){
drh58ad5802011-03-23 22:02:23 +0000546 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000547 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000548
549 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000550 if( zName==0 ){
551 /* If no zName is given, restore all system calls to their default
552 ** settings and return NULL
553 */
dan51438a72011-04-02 17:00:47 +0000554 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000555 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
556 if( aSyscall[i].pDefault ){
557 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000558 }
559 }
560 }else{
561 /* If zName is specified, operate on only the one system call
562 ** specified.
563 */
564 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
565 if( strcmp(zName, aSyscall[i].zName)==0 ){
566 if( aSyscall[i].pDefault==0 ){
567 aSyscall[i].pDefault = aSyscall[i].pCurrent;
568 }
drh1df30962011-03-02 19:06:42 +0000569 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000570 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
571 aSyscall[i].pCurrent = pNewFunc;
572 break;
573 }
574 }
575 }
576 return rc;
577}
578
drh1df30962011-03-02 19:06:42 +0000579/*
580** Return the value of a system call. Return NULL if zName is not a
581** recognized system call name. NULL is also returned if the system call
582** is currently undefined.
583*/
drh58ad5802011-03-23 22:02:23 +0000584static sqlite3_syscall_ptr unixGetSystemCall(
585 sqlite3_vfs *pNotUsed,
586 const char *zName
587){
588 unsigned int i;
589
590 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000591 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
592 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
593 }
594 return 0;
595}
596
597/*
598** Return the name of the first system call after zName. If zName==NULL
599** then return the name of the first system call. Return NULL if zName
600** is the last system call or if zName is not the name of a valid
601** system call.
602*/
603static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000604 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000605
606 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000607 if( zName ){
608 for(i=0; i<ArraySize(aSyscall)-1; i++){
609 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000610 }
611 }
dan0fd7d862011-03-29 10:04:23 +0000612 for(i++; i<ArraySize(aSyscall); i++){
613 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000614 }
615 return 0;
616}
617
drhad4f1e52011-03-04 15:43:57 +0000618/*
drh77a3fdc2013-08-30 14:24:12 +0000619** Do not accept any file descriptor less than this value, in order to avoid
620** opening database file using file descriptors that are commonly used for
621** standard input, output, and error.
622*/
623#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
624# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
625#endif
626
627/*
drh8c815d12012-02-13 20:16:37 +0000628** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000629** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000630**
631** If the file creation mode "m" is 0 then set it to the default for
632** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
633** 0644) as modified by the system umask. If m is not 0, then
634** make the file creation mode be exactly m ignoring the umask.
635**
636** The m parameter will be non-zero only when creating -wal, -journal,
637** and -shm files. We want those files to have *exactly* the same
638** permissions as their original database, unadulterated by the umask.
639** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
640** transaction crashes and leaves behind hot journals, then any
641** process that is able to write to the database will also be able to
642** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000643*/
drh8c815d12012-02-13 20:16:37 +0000644static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000645 int fd;
drhe1186ab2013-01-04 20:45:13 +0000646 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000647 while(1){
drh5adc60b2012-04-14 13:25:11 +0000648#if defined(O_CLOEXEC)
649 fd = osOpen(z,f|O_CLOEXEC,m2);
650#else
651 fd = osOpen(z,f,m2);
652#endif
drh5128d002013-08-30 06:20:23 +0000653 if( fd<0 ){
654 if( errno==EINTR ) continue;
655 break;
656 }
drh77a3fdc2013-08-30 14:24:12 +0000657 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000658 osClose(fd);
659 sqlite3_log(SQLITE_WARNING,
660 "attempt to open \"%s\" as file descriptor %d", z, fd);
661 fd = -1;
662 if( osOpen("/dev/null", f, m)<0 ) break;
663 }
drhe1186ab2013-01-04 20:45:13 +0000664 if( fd>=0 ){
665 if( m!=0 ){
666 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000667 if( osFstat(fd, &statbuf)==0
668 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000669 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000670 ){
drhe1186ab2013-01-04 20:45:13 +0000671 osFchmod(fd, m);
672 }
673 }
drh5adc60b2012-04-14 13:25:11 +0000674#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000675 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000676#endif
drhe1186ab2013-01-04 20:45:13 +0000677 }
drh5adc60b2012-04-14 13:25:11 +0000678 return fd;
drhad4f1e52011-03-04 15:43:57 +0000679}
danielk197713adf8a2004-06-03 16:08:41 +0000680
drh107886a2008-11-21 22:21:50 +0000681/*
dan9359c7b2009-08-21 08:29:10 +0000682** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000683** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000684** vxworksFileId objects used by this file, all of which may be
685** shared by multiple threads.
686**
687** Function unixMutexHeld() is used to assert() that the global mutex
688** is held when required. This function is only used as part of assert()
689** statements. e.g.
690**
691** unixEnterMutex()
692** assert( unixMutexHeld() );
693** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000694*/
695static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000696 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000697}
698static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000699 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000700}
dan9359c7b2009-08-21 08:29:10 +0000701#ifdef SQLITE_DEBUG
702static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000703 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000704}
705#endif
drh107886a2008-11-21 22:21:50 +0000706
drh734c9862008-11-28 15:37:20 +0000707
mistachkinfb383e92015-04-16 03:24:38 +0000708#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000709/*
710** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000711** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000712** integer lock-type.
713*/
drh308c2a52010-05-14 11:30:18 +0000714static const char *azFileLock(int eFileLock){
715 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000716 case NO_LOCK: return "NONE";
717 case SHARED_LOCK: return "SHARED";
718 case RESERVED_LOCK: return "RESERVED";
719 case PENDING_LOCK: return "PENDING";
720 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000721 }
722 return "ERROR";
723}
724#endif
725
726#ifdef SQLITE_LOCK_TRACE
727/*
728** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000729**
drh734c9862008-11-28 15:37:20 +0000730** This routine is used for troubleshooting locks on multithreaded
731** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
732** command-line option on the compiler. This code is normally
733** turned off.
734*/
735static int lockTrace(int fd, int op, struct flock *p){
736 char *zOpName, *zType;
737 int s;
738 int savedErrno;
739 if( op==F_GETLK ){
740 zOpName = "GETLK";
741 }else if( op==F_SETLK ){
742 zOpName = "SETLK";
743 }else{
drh99ab3b12011-03-02 15:09:07 +0000744 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000745 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
746 return s;
747 }
748 if( p->l_type==F_RDLCK ){
749 zType = "RDLCK";
750 }else if( p->l_type==F_WRLCK ){
751 zType = "WRLCK";
752 }else if( p->l_type==F_UNLCK ){
753 zType = "UNLCK";
754 }else{
755 assert( 0 );
756 }
757 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000758 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000759 savedErrno = errno;
760 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
761 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
762 (int)p->l_pid, s);
763 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
764 struct flock l2;
765 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000766 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000767 if( l2.l_type==F_RDLCK ){
768 zType = "RDLCK";
769 }else if( l2.l_type==F_WRLCK ){
770 zType = "WRLCK";
771 }else if( l2.l_type==F_UNLCK ){
772 zType = "UNLCK";
773 }else{
774 assert( 0 );
775 }
776 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
777 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
778 }
779 errno = savedErrno;
780 return s;
781}
drh99ab3b12011-03-02 15:09:07 +0000782#undef osFcntl
783#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000784#endif /* SQLITE_LOCK_TRACE */
785
drhff812312011-02-23 13:33:46 +0000786/*
787** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000788**
drhe6d41732015-02-21 00:49:00 +0000789** All calls to ftruncate() within this file should be made through
790** this wrapper. On the Android platform, bypassing the logic below
791** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000792*/
drhff812312011-02-23 13:33:46 +0000793static int robust_ftruncate(int h, sqlite3_int64 sz){
794 int rc;
dan2ee53412014-09-06 16:49:40 +0000795#ifdef __ANDROID__
796 /* On Android, ftruncate() always uses 32-bit offsets, even if
797 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000798 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000799 ** such attempts. */
800 if( sz>(sqlite3_int64)0x7FFFFFFF ){
801 rc = SQLITE_OK;
802 }else
803#endif
drh99ab3b12011-03-02 15:09:07 +0000804 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000805 return rc;
806}
drh734c9862008-11-28 15:37:20 +0000807
808/*
809** This routine translates a standard POSIX errno code into something
810** useful to the clients of the sqlite3 functions. Specifically, it is
811** intended to translate a variety of "try again" errors into SQLITE_BUSY
812** and a variety of "please close the file descriptor NOW" errors into
813** SQLITE_IOERR
814**
815** Errors during initialization of locks, or file system support for locks,
816** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
817*/
818static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000819 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
820 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
821 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
822 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000823 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000824 case EACCES:
drh734c9862008-11-28 15:37:20 +0000825 case EAGAIN:
826 case ETIMEDOUT:
827 case EBUSY:
828 case EINTR:
829 case ENOLCK:
830 /* random NFS retry error, unless during file system support
831 * introspection, in which it actually means what it says */
832 return SQLITE_BUSY;
833
drh734c9862008-11-28 15:37:20 +0000834 case EPERM:
835 return SQLITE_PERM;
836
drh734c9862008-11-28 15:37:20 +0000837 default:
838 return sqliteIOErr;
839 }
840}
841
842
drh734c9862008-11-28 15:37:20 +0000843/******************************************************************************
844****************** Begin Unique File ID Utility Used By VxWorks ***************
845**
846** On most versions of unix, we can get a unique ID for a file by concatenating
847** the device number and the inode number. But this does not work on VxWorks.
848** On VxWorks, a unique file id must be based on the canonical filename.
849**
850** A pointer to an instance of the following structure can be used as a
851** unique file ID in VxWorks. Each instance of this structure contains
852** a copy of the canonical filename. There is also a reference count.
853** The structure is reclaimed when the number of pointers to it drops to
854** zero.
855**
856** There are never very many files open at one time and lookups are not
857** a performance-critical path, so it is sufficient to put these
858** structures on a linked list.
859*/
860struct vxworksFileId {
861 struct vxworksFileId *pNext; /* Next in a list of them all */
862 int nRef; /* Number of references to this one */
863 int nName; /* Length of the zCanonicalName[] string */
864 char *zCanonicalName; /* Canonical filename */
865};
866
867#if OS_VXWORKS
868/*
drh9b35ea62008-11-29 02:20:26 +0000869** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000870** variable:
871*/
872static struct vxworksFileId *vxworksFileList = 0;
873
874/*
875** Simplify a filename into its canonical form
876** by making the following changes:
877**
878** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000879** * convert /./ into just /
880** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000881**
882** Changes are made in-place. Return the new name length.
883**
884** The original filename is in z[0..n-1]. Return the number of
885** characters in the simplified name.
886*/
887static int vxworksSimplifyName(char *z, int n){
888 int i, j;
889 while( n>1 && z[n-1]=='/' ){ n--; }
890 for(i=j=0; i<n; i++){
891 if( z[i]=='/' ){
892 if( z[i+1]=='/' ) continue;
893 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
894 i += 1;
895 continue;
896 }
897 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
898 while( j>0 && z[j-1]!='/' ){ j--; }
899 if( j>0 ){ j--; }
900 i += 2;
901 continue;
902 }
903 }
904 z[j++] = z[i];
905 }
906 z[j] = 0;
907 return j;
908}
909
910/*
911** Find a unique file ID for the given absolute pathname. Return
912** a pointer to the vxworksFileId object. This pointer is the unique
913** file ID.
914**
915** The nRef field of the vxworksFileId object is incremented before
916** the object is returned. A new vxworksFileId object is created
917** and added to the global list if necessary.
918**
919** If a memory allocation error occurs, return NULL.
920*/
921static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
922 struct vxworksFileId *pNew; /* search key and new file ID */
923 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
924 int n; /* Length of zAbsoluteName string */
925
926 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000927 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000928 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000929 if( pNew==0 ) return 0;
930 pNew->zCanonicalName = (char*)&pNew[1];
931 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
932 n = vxworksSimplifyName(pNew->zCanonicalName, n);
933
934 /* Search for an existing entry that matching the canonical name.
935 ** If found, increment the reference count and return a pointer to
936 ** the existing file ID.
937 */
938 unixEnterMutex();
939 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
940 if( pCandidate->nName==n
941 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
942 ){
943 sqlite3_free(pNew);
944 pCandidate->nRef++;
945 unixLeaveMutex();
946 return pCandidate;
947 }
948 }
949
950 /* No match was found. We will make a new file ID */
951 pNew->nRef = 1;
952 pNew->nName = n;
953 pNew->pNext = vxworksFileList;
954 vxworksFileList = pNew;
955 unixLeaveMutex();
956 return pNew;
957}
958
959/*
960** Decrement the reference count on a vxworksFileId object. Free
961** the object when the reference count reaches zero.
962*/
963static void vxworksReleaseFileId(struct vxworksFileId *pId){
964 unixEnterMutex();
965 assert( pId->nRef>0 );
966 pId->nRef--;
967 if( pId->nRef==0 ){
968 struct vxworksFileId **pp;
969 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
970 assert( *pp==pId );
971 *pp = pId->pNext;
972 sqlite3_free(pId);
973 }
974 unixLeaveMutex();
975}
976#endif /* OS_VXWORKS */
977/*************** End of Unique File ID Utility Used By VxWorks ****************
978******************************************************************************/
979
980
981/******************************************************************************
982*************************** Posix Advisory Locking ****************************
983**
drh9b35ea62008-11-29 02:20:26 +0000984** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000985** section 6.5.2.2 lines 483 through 490 specify that when a process
986** sets or clears a lock, that operation overrides any prior locks set
987** by the same process. It does not explicitly say so, but this implies
988** that it overrides locks set by the same process using a different
989** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000990**
991** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000992** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
993**
994** Suppose ./file1 and ./file2 are really the same file (because
995** one is a hard or symbolic link to the other) then if you set
996** an exclusive lock on fd1, then try to get an exclusive lock
997** on fd2, it works. I would have expected the second lock to
998** fail since there was already a lock on the file due to fd1.
999** But not so. Since both locks came from the same process, the
1000** second overrides the first, even though they were on different
1001** file descriptors opened on different file names.
1002**
drh734c9862008-11-28 15:37:20 +00001003** This means that we cannot use POSIX locks to synchronize file access
1004** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001005** to synchronize access for threads in separate processes, but not
1006** threads within the same process.
1007**
1008** To work around the problem, SQLite has to manage file locks internally
1009** on its own. Whenever a new database is opened, we have to find the
1010** specific inode of the database file (the inode is determined by the
1011** st_dev and st_ino fields of the stat structure that fstat() fills in)
1012** and check for locks already existing on that inode. When locks are
1013** created or removed, we have to look at our own internal record of the
1014** locks to see if another thread has previously set a lock on that same
1015** inode.
1016**
drh9b35ea62008-11-29 02:20:26 +00001017** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1018** For VxWorks, we have to use the alternative unique ID system based on
1019** canonical filename and implemented in the previous division.)
1020**
danielk1977ad94b582007-08-20 06:44:22 +00001021** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001022** descriptor. It is now a structure that holds the integer file
1023** descriptor and a pointer to a structure that describes the internal
1024** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001025** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001026** point to the same locking structure. The locking structure keeps
1027** a reference count (so we will know when to delete it) and a "cnt"
1028** field that tells us its internal lock status. cnt==0 means the
1029** file is unlocked. cnt==-1 means the file has an exclusive lock.
1030** cnt>0 means there are cnt shared locks on the file.
1031**
1032** Any attempt to lock or unlock a file first checks the locking
1033** structure. The fcntl() system call is only invoked to set a
1034** POSIX lock if the internal lock structure transitions between
1035** a locked and an unlocked state.
1036**
drh734c9862008-11-28 15:37:20 +00001037** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001038**
1039** If you close a file descriptor that points to a file that has locks,
1040** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001041** released. To work around this problem, each unixInodeInfo object
1042** maintains a count of the number of pending locks on tha inode.
1043** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001044** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001045** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001046** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001047** be closed and that list is walked (and cleared) when the last lock
1048** clears.
1049**
drh9b35ea62008-11-29 02:20:26 +00001050** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001051**
drh9b35ea62008-11-29 02:20:26 +00001052** Many older versions of linux use the LinuxThreads library which is
1053** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001054** A cannot be modified or overridden by a different thread B.
1055** Only thread A can modify the lock. Locking behavior is correct
1056** if the appliation uses the newer Native Posix Thread Library (NPTL)
1057** on linux - with NPTL a lock created by thread A can override locks
1058** in thread B. But there is no way to know at compile-time which
1059** threading library is being used. So there is no way to know at
1060** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001061** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001062** current process.
drh5fdae772004-06-29 03:29:00 +00001063**
drh8af6c222010-05-14 12:43:01 +00001064** SQLite used to support LinuxThreads. But support for LinuxThreads
1065** was dropped beginning with version 3.7.0. SQLite will still work with
1066** LinuxThreads provided that (1) there is no more than one connection
1067** per database file in the same process and (2) database connections
1068** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001069*/
1070
1071/*
1072** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001073** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001074*/
1075struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001076 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001077#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001078 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001079#else
drh25ef7f52016-12-05 20:06:45 +00001080 /* We are told that some versions of Android contain a bug that
1081 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1082 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1083 ** To work around this, always allocate 64-bits for the inode number.
1084 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1085 ** but that should not be a big deal. */
1086 /* WAS: ino_t ino; */
1087 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001088#endif
1089};
1090
1091/*
drhbbd42a62004-05-22 17:41:58 +00001092** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001093** inode. Or, on LinuxThreads, there is one of these structures for
1094** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001095**
danielk1977ad94b582007-08-20 06:44:22 +00001096** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001097** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001098** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001099*/
drh8af6c222010-05-14 12:43:01 +00001100struct unixInodeInfo {
1101 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001102 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001103 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1104 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001105 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001106 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1107 int nLock; /* Number of outstanding file locks */
1108 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1109 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1110 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001111#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001112 unsigned long long sharedByte; /* for AFP simulated shared lock */
1113#endif
drh6c7d5c52008-11-21 20:32:33 +00001114#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001115 sem_t *pSem; /* Named POSIX semaphore */
1116 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001117#endif
drhbbd42a62004-05-22 17:41:58 +00001118};
1119
drhda0e7682008-07-30 15:27:54 +00001120/*
drh8af6c222010-05-14 12:43:01 +00001121** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001122*/
drhc68886b2017-08-18 16:09:52 +00001123static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
1124static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
drh5fdae772004-06-29 03:29:00 +00001125
drh5fdae772004-06-29 03:29:00 +00001126/*
dane18d4952011-02-21 11:46:24 +00001127**
drhaaeaa182015-11-24 15:12:47 +00001128** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001129** unixLogError().
1130**
1131** It is invoked after an error occurs in an OS function and errno has been
1132** set. It logs a message using sqlite3_log() containing the current value of
1133** errno and, if possible, the human-readable equivalent from strerror() or
1134** strerror_r().
1135**
1136** The first argument passed to the macro should be the error code that
1137** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1138** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001139** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001140** if any.
1141*/
drh0e9365c2011-03-02 02:08:13 +00001142#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1143static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001144 int errcode, /* SQLite error code */
1145 const char *zFunc, /* Name of OS function that failed */
1146 const char *zPath, /* File path associated with error */
1147 int iLine /* Source line number where error occurred */
1148){
1149 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001150 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001151
1152 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1153 ** the strerror() function to obtain the human-readable error message
1154 ** equivalent to errno. Otherwise, use strerror_r().
1155 */
1156#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1157 char aErr[80];
1158 memset(aErr, 0, sizeof(aErr));
1159 zErr = aErr;
1160
1161 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001162 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001163 ** returns a pointer to a buffer containing the error message. That pointer
1164 ** may point to aErr[], or it may point to some static storage somewhere.
1165 ** Otherwise, assume that the system provides the POSIX version of
1166 ** strerror_r(), which always writes an error message into aErr[].
1167 **
1168 ** If the code incorrectly assumes that it is the POSIX version that is
1169 ** available, the error message will often be an empty string. Not a
1170 ** huge problem. Incorrectly concluding that the GNU version is available
1171 ** could lead to a segfault though.
1172 */
1173#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1174 zErr =
1175# endif
drh0e9365c2011-03-02 02:08:13 +00001176 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001177
1178#elif SQLITE_THREADSAFE
1179 /* This is a threadsafe build, but strerror_r() is not available. */
1180 zErr = "";
1181#else
1182 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001183 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001184#endif
1185
drh0e9365c2011-03-02 02:08:13 +00001186 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001187 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001188 "os_unix.c:%d: (%d) %s(%s) - %s",
1189 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001190 );
1191
1192 return errcode;
1193}
1194
drh0e9365c2011-03-02 02:08:13 +00001195/*
1196** Close a file descriptor.
1197**
1198** We assume that close() almost always works, since it is only in a
1199** very sick application or on a very sick platform that it might fail.
1200** If it does fail, simply leak the file descriptor, but do log the
1201** error.
1202**
1203** Note that it is not safe to retry close() after EINTR since the
1204** file descriptor might have already been reused by another thread.
1205** So we don't even try to recover from an EINTR. Just log the error
1206** and move on.
1207*/
1208static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001209 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001210 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1211 pFile ? pFile->zPath : 0, lineno);
1212 }
1213}
dane18d4952011-02-21 11:46:24 +00001214
1215/*
drhe6d41732015-02-21 00:49:00 +00001216** Set the pFile->lastErrno. Do this in a subroutine as that provides
1217** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001218*/
1219static void storeLastErrno(unixFile *pFile, int error){
1220 pFile->lastErrno = error;
1221}
1222
1223/*
danb0ac3e32010-06-16 10:55:42 +00001224** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001225*/
drh0e9365c2011-03-02 02:08:13 +00001226static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001227 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001228 UnixUnusedFd *p;
1229 UnixUnusedFd *pNext;
1230 for(p=pInode->pUnused; p; p=pNext){
1231 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001232 robust_close(pFile, p->fd, __LINE__);
1233 sqlite3_free(p);
drhc68886b2017-08-18 16:09:52 +00001234 nUnusedFd--;
danb0ac3e32010-06-16 10:55:42 +00001235 }
drh0e9365c2011-03-02 02:08:13 +00001236 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001237}
1238
1239/*
drh8af6c222010-05-14 12:43:01 +00001240** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001241**
1242** The mutex entered using the unixEnterMutex() function must be held
1243** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001244*/
danb0ac3e32010-06-16 10:55:42 +00001245static void releaseInodeInfo(unixFile *pFile){
1246 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001247 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001248 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001249 pInode->nRef--;
1250 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001251 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001252 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001253 if( pInode->pPrev ){
1254 assert( pInode->pPrev->pNext==pInode );
1255 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001256 }else{
drh8af6c222010-05-14 12:43:01 +00001257 assert( inodeList==pInode );
1258 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001259 }
drh8af6c222010-05-14 12:43:01 +00001260 if( pInode->pNext ){
1261 assert( pInode->pNext->pPrev==pInode );
1262 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001263 }
drh8af6c222010-05-14 12:43:01 +00001264 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001265 }
drhbbd42a62004-05-22 17:41:58 +00001266 }
drhc68886b2017-08-18 16:09:52 +00001267 assert( inodeList!=0 || nUnusedFd==0 );
drhbbd42a62004-05-22 17:41:58 +00001268}
1269
1270/*
drh8af6c222010-05-14 12:43:01 +00001271** Given a file descriptor, locate the unixInodeInfo object that
1272** describes that file descriptor. Create a new one if necessary. The
1273** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001274**
dan9359c7b2009-08-21 08:29:10 +00001275** The mutex entered using the unixEnterMutex() function must be held
1276** when this function is called.
1277**
drh6c7d5c52008-11-21 20:32:33 +00001278** Return an appropriate error code.
1279*/
drh8af6c222010-05-14 12:43:01 +00001280static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001281 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001282 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001283){
1284 int rc; /* System call return code */
1285 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001286 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1287 struct stat statbuf; /* Low-level file information */
1288 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001289
dan9359c7b2009-08-21 08:29:10 +00001290 assert( unixMutexHeld() );
1291
drh6c7d5c52008-11-21 20:32:33 +00001292 /* Get low-level information about the file that we can used to
1293 ** create a unique name for the file.
1294 */
1295 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001296 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001297 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001298 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001299#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001300 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1301#endif
1302 return SQLITE_IOERR;
1303 }
1304
drheb0d74f2009-02-03 15:27:02 +00001305#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001306 /* On OS X on an msdos filesystem, the inode number is reported
1307 ** incorrectly for zero-size files. See ticket #3260. To work
1308 ** around this problem (we consider it a bug in OS X, not SQLite)
1309 ** we always increase the file size to 1 by writing a single byte
1310 ** prior to accessing the inode number. The one byte written is
1311 ** an ASCII 'S' character which also happens to be the first byte
1312 ** in the header of every SQLite database. In this way, if there
1313 ** is a race condition such that another thread has already populated
1314 ** the first page of the database, no damage is done.
1315 */
drh7ed97b92010-01-20 13:07:21 +00001316 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001317 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001318 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001319 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001320 return SQLITE_IOERR;
1321 }
drh99ab3b12011-03-02 15:09:07 +00001322 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001323 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001324 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001325 return SQLITE_IOERR;
1326 }
1327 }
drheb0d74f2009-02-03 15:27:02 +00001328#endif
drh6c7d5c52008-11-21 20:32:33 +00001329
drh8af6c222010-05-14 12:43:01 +00001330 memset(&fileId, 0, sizeof(fileId));
1331 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001332#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001333 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001334#else
drh25ef7f52016-12-05 20:06:45 +00001335 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001336#endif
drhc68886b2017-08-18 16:09:52 +00001337 assert( inodeList!=0 || nUnusedFd==0 );
drh8af6c222010-05-14 12:43:01 +00001338 pInode = inodeList;
1339 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1340 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001341 }
drh8af6c222010-05-14 12:43:01 +00001342 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001343 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001344 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001345 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001346 }
drh8af6c222010-05-14 12:43:01 +00001347 memset(pInode, 0, sizeof(*pInode));
1348 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1349 pInode->nRef = 1;
1350 pInode->pNext = inodeList;
1351 pInode->pPrev = 0;
1352 if( inodeList ) inodeList->pPrev = pInode;
1353 inodeList = pInode;
1354 }else{
1355 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001356 }
drh8af6c222010-05-14 12:43:01 +00001357 *ppInode = pInode;
1358 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001359}
drh6c7d5c52008-11-21 20:32:33 +00001360
drhb959a012013-12-07 12:29:22 +00001361/*
1362** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1363*/
1364static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001365#if OS_VXWORKS
1366 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1367#else
drhb959a012013-12-07 12:29:22 +00001368 struct stat buf;
1369 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001370 (osStat(pFile->zPath, &buf)!=0
1371 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001372#endif
drhb959a012013-12-07 12:29:22 +00001373}
1374
aswift5b1a2562008-08-22 00:22:35 +00001375
1376/*
drhfbc7e882013-04-11 01:16:15 +00001377** Check a unixFile that is a database. Verify the following:
1378**
1379** (1) There is exactly one hard link on the file
1380** (2) The file is not a symbolic link
1381** (3) The file has not been renamed or unlinked
1382**
1383** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1384*/
1385static void verifyDbFile(unixFile *pFile){
1386 struct stat buf;
1387 int rc;
drh86151e82015-12-08 14:37:16 +00001388
1389 /* These verifications occurs for the main database only */
1390 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1391
drhfbc7e882013-04-11 01:16:15 +00001392 rc = osFstat(pFile->h, &buf);
1393 if( rc!=0 ){
1394 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001395 return;
1396 }
drh6369bc32016-03-21 16:06:42 +00001397 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001398 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001399 return;
1400 }
1401 if( buf.st_nlink>1 ){
1402 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001403 return;
1404 }
drhb959a012013-12-07 12:29:22 +00001405 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001406 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001407 return;
1408 }
1409}
1410
1411
1412/*
danielk197713adf8a2004-06-03 16:08:41 +00001413** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001414** file by this or any other process. If such a lock is held, set *pResOut
1415** to a non-zero value otherwise *pResOut is set to zero. The return value
1416** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001417*/
danielk1977861f7452008-06-05 11:39:11 +00001418static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001419 int rc = SQLITE_OK;
1420 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001421 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001422
danielk1977861f7452008-06-05 11:39:11 +00001423 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1424
drh054889e2005-11-30 03:20:31 +00001425 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001426 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001427 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001428
1429 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001430 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001431 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001432 }
1433
drh2ac3ee92004-06-07 16:27:46 +00001434 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001435 */
danielk197709480a92009-02-09 05:32:32 +00001436#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001437 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001438 struct flock lock;
1439 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001440 lock.l_start = RESERVED_BYTE;
1441 lock.l_len = 1;
1442 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001443 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1444 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001445 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001446 } else if( lock.l_type!=F_UNLCK ){
1447 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001448 }
1449 }
danielk197709480a92009-02-09 05:32:32 +00001450#endif
danielk197713adf8a2004-06-03 16:08:41 +00001451
drh6c7d5c52008-11-21 20:32:33 +00001452 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001453 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001454
aswift5b1a2562008-08-22 00:22:35 +00001455 *pResOut = reserved;
1456 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001457}
1458
1459/*
drha7e61d82011-03-12 17:02:57 +00001460** Attempt to set a system-lock on the file pFile. The lock is
1461** described by pLock.
1462**
drh77197112011-03-15 19:08:48 +00001463** If the pFile was opened read/write from unix-excl, then the only lock
1464** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001465** the first time any lock is attempted. All subsequent system locking
1466** operations become no-ops. Locking operations still happen internally,
1467** in order to coordinate access between separate database connections
1468** within this process, but all of that is handled in memory and the
1469** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001470**
1471** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1472** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1473** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001474**
1475** Zero is returned if the call completes successfully, or -1 if a call
1476** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001477*/
1478static int unixFileLock(unixFile *pFile, struct flock *pLock){
1479 int rc;
drh3cb93392011-03-12 18:10:44 +00001480 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001481 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001482 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001483 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001484 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001485 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001486 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001487 lock.l_whence = SEEK_SET;
1488 lock.l_start = SHARED_FIRST;
1489 lock.l_len = SHARED_SIZE;
1490 lock.l_type = F_WRLCK;
1491 rc = osFcntl(pFile->h, F_SETLK, &lock);
1492 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001493 pInode->bProcessLock = 1;
1494 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001495 }else{
1496 rc = 0;
1497 }
1498 }else{
1499 rc = osFcntl(pFile->h, F_SETLK, pLock);
1500 }
1501 return rc;
1502}
1503
1504/*
drh308c2a52010-05-14 11:30:18 +00001505** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001506** of the following:
1507**
drh2ac3ee92004-06-07 16:27:46 +00001508** (1) SHARED_LOCK
1509** (2) RESERVED_LOCK
1510** (3) PENDING_LOCK
1511** (4) EXCLUSIVE_LOCK
1512**
drhb3e04342004-06-08 00:47:47 +00001513** Sometimes when requesting one lock state, additional lock states
1514** are inserted in between. The locking might fail on one of the later
1515** transitions leaving the lock state different from what it started but
1516** still short of its goal. The following chart shows the allowed
1517** transitions and the inserted intermediate states:
1518**
1519** UNLOCKED -> SHARED
1520** SHARED -> RESERVED
1521** SHARED -> (PENDING) -> EXCLUSIVE
1522** RESERVED -> (PENDING) -> EXCLUSIVE
1523** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001524**
drha6abd042004-06-09 17:37:22 +00001525** This routine will only increase a lock. Use the sqlite3OsUnlock()
1526** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001527*/
drh308c2a52010-05-14 11:30:18 +00001528static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001529 /* The following describes the implementation of the various locks and
1530 ** lock transitions in terms of the POSIX advisory shared and exclusive
1531 ** lock primitives (called read-locks and write-locks below, to avoid
1532 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001533 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001534 ** accessing the same database file, in case that is ever required.
1535 **
1536 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1537 ** byte', each single bytes at well known offsets, and the 'shared byte
1538 ** range', a range of 510 bytes at a well known offset.
1539 **
1540 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001541 ** byte'. If this is successful, 'shared byte range' is read-locked
1542 ** and the lock on the 'pending byte' released. (Legacy note: When
1543 ** SQLite was first developed, Windows95 systems were still very common,
1544 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1545 ** single randomly selected by from the 'shared byte range' is locked.
1546 ** Windows95 is now pretty much extinct, but this work-around for the
1547 ** lack of shared-locks on Windows95 lives on, for backwards
1548 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001549 **
danielk197790ba3bd2004-06-25 08:32:25 +00001550 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1551 ** A RESERVED lock is implemented by grabbing a write-lock on the
1552 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001553 **
1554 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001555 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1556 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1557 ** obtained, but existing SHARED locks are allowed to persist. A process
1558 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1559 ** This property is used by the algorithm for rolling back a journal file
1560 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001561 **
danielk197790ba3bd2004-06-25 08:32:25 +00001562 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1563 ** implemented by obtaining a write-lock on the entire 'shared byte
1564 ** range'. Since all other locks require a read-lock on one of the bytes
1565 ** within this range, this ensures that no other locks are held on the
1566 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001567 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001568 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001569 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001570 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001571 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001572 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001573
drh054889e2005-11-30 03:20:31 +00001574 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001575 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1576 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001577 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001578 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001579
1580 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001581 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001582 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001583 */
drh308c2a52010-05-14 11:30:18 +00001584 if( pFile->eFileLock>=eFileLock ){
1585 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1586 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001587 return SQLITE_OK;
1588 }
1589
drh0c2694b2009-09-03 16:23:44 +00001590 /* Make sure the locking sequence is correct.
1591 ** (1) We never move from unlocked to anything higher than shared lock.
1592 ** (2) SQLite never explicitly requests a pendig lock.
1593 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001594 */
drh308c2a52010-05-14 11:30:18 +00001595 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1596 assert( eFileLock!=PENDING_LOCK );
1597 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001598
drh8af6c222010-05-14 12:43:01 +00001599 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001600 */
drh6c7d5c52008-11-21 20:32:33 +00001601 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001602 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001603
danielk1977ad94b582007-08-20 06:44:22 +00001604 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001605 ** handle that precludes the requested lock, return BUSY.
1606 */
drh8af6c222010-05-14 12:43:01 +00001607 if( (pFile->eFileLock!=pInode->eFileLock &&
1608 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001609 ){
1610 rc = SQLITE_BUSY;
1611 goto end_lock;
1612 }
1613
1614 /* If a SHARED lock is requested, and some thread using this PID already
1615 ** has a SHARED or RESERVED lock, then increment reference counts and
1616 ** return SQLITE_OK.
1617 */
drh308c2a52010-05-14 11:30:18 +00001618 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001619 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001620 assert( eFileLock==SHARED_LOCK );
1621 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001622 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001623 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001624 pInode->nShared++;
1625 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001626 goto end_lock;
1627 }
1628
danielk19779a1d0ab2004-06-01 14:09:28 +00001629
drh3cde3bb2004-06-12 02:17:14 +00001630 /* A PENDING lock is needed before acquiring a SHARED lock and before
1631 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1632 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001633 */
drh0c2694b2009-09-03 16:23:44 +00001634 lock.l_len = 1L;
1635 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001636 if( eFileLock==SHARED_LOCK
1637 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001638 ){
drh308c2a52010-05-14 11:30:18 +00001639 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001640 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001641 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001642 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001643 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001644 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001645 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001646 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001647 goto end_lock;
1648 }
drh3cde3bb2004-06-12 02:17:14 +00001649 }
1650
1651
1652 /* If control gets to this point, then actually go ahead and make
1653 ** operating system calls for the specified lock.
1654 */
drh308c2a52010-05-14 11:30:18 +00001655 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001656 assert( pInode->nShared==0 );
1657 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001658 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001659
drh2ac3ee92004-06-07 16:27:46 +00001660 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001661 lock.l_start = SHARED_FIRST;
1662 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001663 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001664 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001665 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001666 }
dan661d71a2011-03-30 19:08:03 +00001667
drh2ac3ee92004-06-07 16:27:46 +00001668 /* Drop the temporary PENDING lock */
1669 lock.l_start = PENDING_BYTE;
1670 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001671 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001672 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1673 /* This could happen with a network mount */
1674 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001675 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001676 }
dan661d71a2011-03-30 19:08:03 +00001677
1678 if( rc ){
1679 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001680 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001681 }
dan661d71a2011-03-30 19:08:03 +00001682 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001683 }else{
drh308c2a52010-05-14 11:30:18 +00001684 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001685 pInode->nLock++;
1686 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001687 }
drh8af6c222010-05-14 12:43:01 +00001688 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001689 /* We are trying for an exclusive lock but another thread in this
1690 ** same process is still holding a shared lock. */
1691 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001692 }else{
drh3cde3bb2004-06-12 02:17:14 +00001693 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001694 ** assumed that there is a SHARED or greater lock on the file
1695 ** already.
1696 */
drh308c2a52010-05-14 11:30:18 +00001697 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001698 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001699
1700 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1701 if( eFileLock==RESERVED_LOCK ){
1702 lock.l_start = RESERVED_BYTE;
1703 lock.l_len = 1L;
1704 }else{
1705 lock.l_start = SHARED_FIRST;
1706 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001707 }
dan661d71a2011-03-30 19:08:03 +00001708
1709 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001710 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001711 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001712 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001713 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001714 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001715 }
drhbbd42a62004-05-22 17:41:58 +00001716 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001717
drh8f941bc2009-01-14 23:03:40 +00001718
drhd3d8c042012-05-29 17:02:40 +00001719#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001720 /* Set up the transaction-counter change checking flags when
1721 ** transitioning from a SHARED to a RESERVED lock. The change
1722 ** from SHARED to RESERVED marks the beginning of a normal
1723 ** write operation (not a hot journal rollback).
1724 */
1725 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001726 && pFile->eFileLock<=SHARED_LOCK
1727 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001728 ){
1729 pFile->transCntrChng = 0;
1730 pFile->dbUpdate = 0;
1731 pFile->inNormalWrite = 1;
1732 }
1733#endif
1734
1735
danielk1977ecb2a962004-06-02 06:30:16 +00001736 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001737 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001738 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001739 }else if( eFileLock==EXCLUSIVE_LOCK ){
1740 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001741 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001742 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001743
1744end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001745 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001746 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1747 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001748 return rc;
1749}
1750
1751/*
dan08da86a2009-08-21 17:18:03 +00001752** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001753** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001754*/
1755static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001756 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001757 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drh8af6c222010-05-14 12:43:01 +00001758 p->pNext = pInode->pUnused;
1759 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001760 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001761 pFile->pPreallocatedUnused = 0;
1762 nUnusedFd++;
dan08da86a2009-08-21 17:18:03 +00001763}
1764
1765/*
drh308c2a52010-05-14 11:30:18 +00001766** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001767** must be either NO_LOCK or SHARED_LOCK.
1768**
1769** If the locking level of the file descriptor is already at or below
1770** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001771**
1772** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1773** the byte range is divided into 2 parts and the first part is unlocked then
1774** set to a read lock, then the other part is simply unlocked. This works
1775** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1776** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001777*/
drha7e61d82011-03-12 17:02:57 +00001778static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001779 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001780 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001781 struct flock lock;
1782 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001783
drh054889e2005-11-30 03:20:31 +00001784 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001785 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001786 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001787 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001788
drh308c2a52010-05-14 11:30:18 +00001789 assert( eFileLock<=SHARED_LOCK );
1790 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001791 return SQLITE_OK;
1792 }
drh6c7d5c52008-11-21 20:32:33 +00001793 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001794 pInode = pFile->pInode;
1795 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001796 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001797 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001798
drhd3d8c042012-05-29 17:02:40 +00001799#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001800 /* When reducing a lock such that other processes can start
1801 ** reading the database file again, make sure that the
1802 ** transaction counter was updated if any part of the database
1803 ** file changed. If the transaction counter is not updated,
1804 ** other connections to the same file might not realize that
1805 ** the file has changed and hence might not know to flush their
1806 ** cache. The use of a stale cache can lead to database corruption.
1807 */
drh8f941bc2009-01-14 23:03:40 +00001808 pFile->inNormalWrite = 0;
1809#endif
1810
drh7ed97b92010-01-20 13:07:21 +00001811 /* downgrading to a shared lock on NFS involves clearing the write lock
1812 ** before establishing the readlock - to avoid a race condition we downgrade
1813 ** the lock in 2 blocks, so that part of the range will be covered by a
1814 ** write lock until the rest is covered by a read lock:
1815 ** 1: [WWWWW]
1816 ** 2: [....W]
1817 ** 3: [RRRRW]
1818 ** 4: [RRRR.]
1819 */
drh308c2a52010-05-14 11:30:18 +00001820 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001821#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001822 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001823 assert( handleNFSUnlock==0 );
1824#endif
1825#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001826 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001827 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001828 off_t divSize = SHARED_SIZE - 1;
1829
1830 lock.l_type = F_UNLCK;
1831 lock.l_whence = SEEK_SET;
1832 lock.l_start = SHARED_FIRST;
1833 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001834 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001835 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001836 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001837 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001838 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001839 }
drh7ed97b92010-01-20 13:07:21 +00001840 lock.l_type = F_RDLCK;
1841 lock.l_whence = SEEK_SET;
1842 lock.l_start = SHARED_FIRST;
1843 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001844 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001845 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001846 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1847 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001848 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001849 }
1850 goto end_unlock;
1851 }
1852 lock.l_type = F_UNLCK;
1853 lock.l_whence = SEEK_SET;
1854 lock.l_start = SHARED_FIRST+divSize;
1855 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001856 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001857 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001858 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001859 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001860 goto end_unlock;
1861 }
drh30f776f2011-02-25 03:25:07 +00001862 }else
1863#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1864 {
drh7ed97b92010-01-20 13:07:21 +00001865 lock.l_type = F_RDLCK;
1866 lock.l_whence = SEEK_SET;
1867 lock.l_start = SHARED_FIRST;
1868 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001869 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001870 /* In theory, the call to unixFileLock() cannot fail because another
1871 ** process is holding an incompatible lock. If it does, this
1872 ** indicates that the other process is not following the locking
1873 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1874 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1875 ** an assert to fail). */
1876 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001877 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001878 goto end_unlock;
1879 }
drh9c105bb2004-10-02 20:38:28 +00001880 }
1881 }
drhbbd42a62004-05-22 17:41:58 +00001882 lock.l_type = F_UNLCK;
1883 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001884 lock.l_start = PENDING_BYTE;
1885 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001886 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001887 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001888 }else{
danea83bc62011-04-01 11:56:32 +00001889 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001890 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001891 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001892 }
drhbbd42a62004-05-22 17:41:58 +00001893 }
drh308c2a52010-05-14 11:30:18 +00001894 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001895 /* Decrement the shared lock counter. Release the lock using an
1896 ** OS call only when all threads in this same process have released
1897 ** the lock.
1898 */
drh8af6c222010-05-14 12:43:01 +00001899 pInode->nShared--;
1900 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001901 lock.l_type = F_UNLCK;
1902 lock.l_whence = SEEK_SET;
1903 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001904 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001905 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001906 }else{
danea83bc62011-04-01 11:56:32 +00001907 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001908 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001909 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001910 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001911 }
drha6abd042004-06-09 17:37:22 +00001912 }
1913
drhbbd42a62004-05-22 17:41:58 +00001914 /* Decrement the count of locks against this same file. When the
1915 ** count reaches zero, close any other file descriptors whose close
1916 ** was deferred because of outstanding locks.
1917 */
drh8af6c222010-05-14 12:43:01 +00001918 pInode->nLock--;
1919 assert( pInode->nLock>=0 );
1920 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001921 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001922 }
1923 }
drhf2f105d2012-08-20 15:53:54 +00001924
aswift5b1a2562008-08-22 00:22:35 +00001925end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001926 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001927 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001928 return rc;
drhbbd42a62004-05-22 17:41:58 +00001929}
1930
1931/*
drh308c2a52010-05-14 11:30:18 +00001932** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001933** must be either NO_LOCK or SHARED_LOCK.
1934**
1935** If the locking level of the file descriptor is already at or below
1936** the requested locking level, this routine is a no-op.
1937*/
drh308c2a52010-05-14 11:30:18 +00001938static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001939#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001940 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001941#endif
drha7e61d82011-03-12 17:02:57 +00001942 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001943}
1944
mistachkine98844f2013-08-24 00:59:24 +00001945#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001946static int unixMapfile(unixFile *pFd, i64 nByte);
1947static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001948#endif
danf23da962013-03-23 21:00:41 +00001949
drh7ed97b92010-01-20 13:07:21 +00001950/*
danielk1977e339d652008-06-28 11:23:00 +00001951** This function performs the parts of the "close file" operation
1952** common to all locking schemes. It closes the directory and file
1953** handles, if they are valid, and sets all fields of the unixFile
1954** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001955**
1956** It is *not* necessary to hold the mutex when this routine is called,
1957** even on VxWorks. A mutex will be acquired on VxWorks by the
1958** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001959*/
1960static int closeUnixFile(sqlite3_file *id){
1961 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001962#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001963 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001964#endif
dan661d71a2011-03-30 19:08:03 +00001965 if( pFile->h>=0 ){
1966 robust_close(pFile, pFile->h, __LINE__);
1967 pFile->h = -1;
1968 }
1969#if OS_VXWORKS
1970 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001971 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001972 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001973 }
1974 vxworksReleaseFileId(pFile->pId);
1975 pFile->pId = 0;
1976 }
1977#endif
drh0bdbc902014-06-16 18:35:06 +00001978#ifdef SQLITE_UNLINK_AFTER_CLOSE
1979 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1980 osUnlink(pFile->zPath);
1981 sqlite3_free(*(char**)&pFile->zPath);
1982 pFile->zPath = 0;
1983 }
1984#endif
dan661d71a2011-03-30 19:08:03 +00001985 OSTRACE(("CLOSE %-3d\n", pFile->h));
1986 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00001987 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00001988 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001989 return SQLITE_OK;
1990}
1991
1992/*
danielk1977e3026632004-06-22 11:29:02 +00001993** Close a file.
1994*/
danielk197762079062007-08-15 17:08:46 +00001995static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001996 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001997 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001998 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001999 unixUnlock(id, NO_LOCK);
2000 unixEnterMutex();
2001
2002 /* unixFile.pInode is always valid here. Otherwise, a different close
2003 ** routine (e.g. nolockClose()) would be called instead.
2004 */
2005 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2006 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
2007 /* If there are outstanding locks, do not actually close the file just
2008 ** yet because that would clear those locks. Instead, add the file
2009 ** descriptor to pInode->pUnused list. It will be automatically closed
2010 ** when the last lock is cleared.
2011 */
2012 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002013 }
dan661d71a2011-03-30 19:08:03 +00002014 releaseInodeInfo(pFile);
2015 rc = closeUnixFile(id);
2016 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002017 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002018}
2019
drh734c9862008-11-28 15:37:20 +00002020/************** End of the posix advisory lock implementation *****************
2021******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002022
drh734c9862008-11-28 15:37:20 +00002023/******************************************************************************
2024****************************** No-op Locking **********************************
2025**
2026** Of the various locking implementations available, this is by far the
2027** simplest: locking is ignored. No attempt is made to lock the database
2028** file for reading or writing.
2029**
2030** This locking mode is appropriate for use on read-only databases
2031** (ex: databases that are burned into CD-ROM, for example.) It can
2032** also be used if the application employs some external mechanism to
2033** prevent simultaneous access of the same database by two or more
2034** database connections. But there is a serious risk of database
2035** corruption if this locking mode is used in situations where multiple
2036** database connections are accessing the same database file at the same
2037** time and one or more of those connections are writing.
2038*/
drhbfe66312006-10-03 17:40:40 +00002039
drh734c9862008-11-28 15:37:20 +00002040static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2041 UNUSED_PARAMETER(NotUsed);
2042 *pResOut = 0;
2043 return SQLITE_OK;
2044}
drh734c9862008-11-28 15:37:20 +00002045static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2046 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2047 return SQLITE_OK;
2048}
drh734c9862008-11-28 15:37:20 +00002049static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2050 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2051 return SQLITE_OK;
2052}
2053
2054/*
drh9b35ea62008-11-29 02:20:26 +00002055** Close the file.
drh734c9862008-11-28 15:37:20 +00002056*/
2057static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002058 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002059}
2060
2061/******************* End of the no-op lock implementation *********************
2062******************************************************************************/
2063
2064/******************************************************************************
2065************************* Begin dot-file Locking ******************************
2066**
mistachkin48864df2013-03-21 21:20:32 +00002067** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002068** files (really a directory) to control access to the database. This works
2069** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002070**
2071** (1) There is zero concurrency. A single reader blocks all other
2072** connections from reading or writing the database.
2073**
2074** (2) An application crash or power loss can leave stale lock files
2075** sitting around that need to be cleared manually.
2076**
2077** Nevertheless, a dotlock is an appropriate locking mode for use if no
2078** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002079**
drh9ef6bc42011-11-04 02:24:02 +00002080** Dotfile locking works by creating a subdirectory in the same directory as
2081** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002082** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002083** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002084*/
2085
2086/*
2087** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002088** lock directory.
drh734c9862008-11-28 15:37:20 +00002089*/
2090#define DOTLOCK_SUFFIX ".lock"
2091
drh7708e972008-11-29 00:56:52 +00002092/*
2093** This routine checks if there is a RESERVED lock held on the specified
2094** file by this or any other process. If such a lock is held, set *pResOut
2095** to a non-zero value otherwise *pResOut is set to zero. The return value
2096** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2097**
2098** In dotfile locking, either a lock exists or it does not. So in this
2099** variation of CheckReservedLock(), *pResOut is set to true if any lock
2100** is held on the file and false if the file is unlocked.
2101*/
drh734c9862008-11-28 15:37:20 +00002102static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2103 int rc = SQLITE_OK;
2104 int reserved = 0;
2105 unixFile *pFile = (unixFile*)id;
2106
2107 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2108
2109 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002110 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002111 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002112 *pResOut = reserved;
2113 return rc;
2114}
2115
drh7708e972008-11-29 00:56:52 +00002116/*
drh308c2a52010-05-14 11:30:18 +00002117** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002118** of the following:
2119**
2120** (1) SHARED_LOCK
2121** (2) RESERVED_LOCK
2122** (3) PENDING_LOCK
2123** (4) EXCLUSIVE_LOCK
2124**
2125** Sometimes when requesting one lock state, additional lock states
2126** are inserted in between. The locking might fail on one of the later
2127** transitions leaving the lock state different from what it started but
2128** still short of its goal. The following chart shows the allowed
2129** transitions and the inserted intermediate states:
2130**
2131** UNLOCKED -> SHARED
2132** SHARED -> RESERVED
2133** SHARED -> (PENDING) -> EXCLUSIVE
2134** RESERVED -> (PENDING) -> EXCLUSIVE
2135** PENDING -> EXCLUSIVE
2136**
2137** This routine will only increase a lock. Use the sqlite3OsUnlock()
2138** routine to lower a locking level.
2139**
2140** With dotfile locking, we really only support state (4): EXCLUSIVE.
2141** But we track the other locking levels internally.
2142*/
drh308c2a52010-05-14 11:30:18 +00002143static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002144 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002145 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002146 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002147
drh7708e972008-11-29 00:56:52 +00002148
2149 /* If we have any lock, then the lock file already exists. All we have
2150 ** to do is adjust our internal record of the lock level.
2151 */
drh308c2a52010-05-14 11:30:18 +00002152 if( pFile->eFileLock > NO_LOCK ){
2153 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002154 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002155#ifdef HAVE_UTIME
2156 utime(zLockFile, NULL);
2157#else
drh734c9862008-11-28 15:37:20 +00002158 utimes(zLockFile, NULL);
2159#endif
drh7708e972008-11-29 00:56:52 +00002160 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002161 }
2162
2163 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002164 rc = osMkdir(zLockFile, 0777);
2165 if( rc<0 ){
2166 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002167 int tErrno = errno;
2168 if( EEXIST == tErrno ){
2169 rc = SQLITE_BUSY;
2170 } else {
2171 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002172 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002173 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002174 }
2175 }
drh7708e972008-11-29 00:56:52 +00002176 return rc;
drh734c9862008-11-28 15:37:20 +00002177 }
drh734c9862008-11-28 15:37:20 +00002178
2179 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002180 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002181 return rc;
2182}
2183
drh7708e972008-11-29 00:56:52 +00002184/*
drh308c2a52010-05-14 11:30:18 +00002185** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002186** must be either NO_LOCK or SHARED_LOCK.
2187**
2188** If the locking level of the file descriptor is already at or below
2189** the requested locking level, this routine is a no-op.
2190**
2191** When the locking level reaches NO_LOCK, delete the lock file.
2192*/
drh308c2a52010-05-14 11:30:18 +00002193static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002194 unixFile *pFile = (unixFile*)id;
2195 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002196 int rc;
drh734c9862008-11-28 15:37:20 +00002197
2198 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002199 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002200 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002201 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002202
2203 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002204 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002205 return SQLITE_OK;
2206 }
drh7708e972008-11-29 00:56:52 +00002207
2208 /* To downgrade to shared, simply update our internal notion of the
2209 ** lock state. No need to mess with the file on disk.
2210 */
drh308c2a52010-05-14 11:30:18 +00002211 if( eFileLock==SHARED_LOCK ){
2212 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002213 return SQLITE_OK;
2214 }
2215
drh7708e972008-11-29 00:56:52 +00002216 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002217 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002218 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002219 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002220 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002221 if( tErrno==ENOENT ){
2222 rc = SQLITE_OK;
2223 }else{
danea83bc62011-04-01 11:56:32 +00002224 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002225 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002226 }
2227 return rc;
2228 }
drh308c2a52010-05-14 11:30:18 +00002229 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002230 return SQLITE_OK;
2231}
2232
2233/*
drh9b35ea62008-11-29 02:20:26 +00002234** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002235*/
2236static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002237 unixFile *pFile = (unixFile*)id;
2238 assert( id!=0 );
2239 dotlockUnlock(id, NO_LOCK);
2240 sqlite3_free(pFile->lockingContext);
2241 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002242}
2243/****************** End of the dot-file lock implementation *******************
2244******************************************************************************/
2245
2246/******************************************************************************
2247************************** Begin flock Locking ********************************
2248**
2249** Use the flock() system call to do file locking.
2250**
drh6b9d6dd2008-12-03 19:34:47 +00002251** flock() locking is like dot-file locking in that the various
2252** fine-grain locking levels supported by SQLite are collapsed into
2253** a single exclusive lock. In other words, SHARED, RESERVED, and
2254** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2255** still works when you do this, but concurrency is reduced since
2256** only a single process can be reading the database at a time.
2257**
drhe89b2912015-03-03 20:42:01 +00002258** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002259*/
drhe89b2912015-03-03 20:42:01 +00002260#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002261
drh6b9d6dd2008-12-03 19:34:47 +00002262/*
drhff812312011-02-23 13:33:46 +00002263** Retry flock() calls that fail with EINTR
2264*/
2265#ifdef EINTR
2266static int robust_flock(int fd, int op){
2267 int rc;
2268 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2269 return rc;
2270}
2271#else
drh5c819272011-02-23 14:00:12 +00002272# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002273#endif
2274
2275
2276/*
drh6b9d6dd2008-12-03 19:34:47 +00002277** This routine checks if there is a RESERVED lock held on the specified
2278** file by this or any other process. If such a lock is held, set *pResOut
2279** to a non-zero value otherwise *pResOut is set to zero. The return value
2280** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2281*/
drh734c9862008-11-28 15:37:20 +00002282static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2283 int rc = SQLITE_OK;
2284 int reserved = 0;
2285 unixFile *pFile = (unixFile*)id;
2286
2287 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2288
2289 assert( pFile );
2290
2291 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002292 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002293 reserved = 1;
2294 }
2295
2296 /* Otherwise see if some other process holds it. */
2297 if( !reserved ){
2298 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002299 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002300 if( !lrc ){
2301 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002302 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002303 if ( lrc ) {
2304 int tErrno = errno;
2305 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002306 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002307 storeLastErrno(pFile, tErrno);
2308 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002309 }
2310 } else {
2311 int tErrno = errno;
2312 reserved = 1;
2313 /* someone else might have it reserved */
2314 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2315 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002316 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002317 rc = lrc;
2318 }
2319 }
2320 }
drh308c2a52010-05-14 11:30:18 +00002321 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002322
2323#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002324 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002325 rc = SQLITE_OK;
2326 reserved=1;
2327 }
2328#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2329 *pResOut = reserved;
2330 return rc;
2331}
2332
drh6b9d6dd2008-12-03 19:34:47 +00002333/*
drh308c2a52010-05-14 11:30:18 +00002334** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002335** of the following:
2336**
2337** (1) SHARED_LOCK
2338** (2) RESERVED_LOCK
2339** (3) PENDING_LOCK
2340** (4) EXCLUSIVE_LOCK
2341**
2342** Sometimes when requesting one lock state, additional lock states
2343** are inserted in between. The locking might fail on one of the later
2344** transitions leaving the lock state different from what it started but
2345** still short of its goal. The following chart shows the allowed
2346** transitions and the inserted intermediate states:
2347**
2348** UNLOCKED -> SHARED
2349** SHARED -> RESERVED
2350** SHARED -> (PENDING) -> EXCLUSIVE
2351** RESERVED -> (PENDING) -> EXCLUSIVE
2352** PENDING -> EXCLUSIVE
2353**
2354** flock() only really support EXCLUSIVE locks. We track intermediate
2355** lock states in the sqlite3_file structure, but all locks SHARED or
2356** above are really EXCLUSIVE locks and exclude all other processes from
2357** access the file.
2358**
2359** This routine will only increase a lock. Use the sqlite3OsUnlock()
2360** routine to lower a locking level.
2361*/
drh308c2a52010-05-14 11:30:18 +00002362static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002363 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002364 unixFile *pFile = (unixFile*)id;
2365
2366 assert( pFile );
2367
2368 /* if we already have a lock, it is exclusive.
2369 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002370 if (pFile->eFileLock > NO_LOCK) {
2371 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002372 return SQLITE_OK;
2373 }
2374
2375 /* grab an exclusive lock */
2376
drhff812312011-02-23 13:33:46 +00002377 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002378 int tErrno = errno;
2379 /* didn't get, must be busy */
2380 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2381 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002382 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002383 }
2384 } else {
2385 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002386 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002387 }
drh308c2a52010-05-14 11:30:18 +00002388 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2389 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002390#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002391 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002392 rc = SQLITE_BUSY;
2393 }
2394#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2395 return rc;
2396}
2397
drh6b9d6dd2008-12-03 19:34:47 +00002398
2399/*
drh308c2a52010-05-14 11:30:18 +00002400** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002401** must be either NO_LOCK or SHARED_LOCK.
2402**
2403** If the locking level of the file descriptor is already at or below
2404** the requested locking level, this routine is a no-op.
2405*/
drh308c2a52010-05-14 11:30:18 +00002406static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002407 unixFile *pFile = (unixFile*)id;
2408
2409 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002410 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002411 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002412 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002413
2414 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002415 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002416 return SQLITE_OK;
2417 }
2418
2419 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002420 if (eFileLock==SHARED_LOCK) {
2421 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002422 return SQLITE_OK;
2423 }
2424
2425 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002426 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002427#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002428 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002429#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002430 return SQLITE_IOERR_UNLOCK;
2431 }else{
drh308c2a52010-05-14 11:30:18 +00002432 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002433 return SQLITE_OK;
2434 }
2435}
2436
2437/*
2438** Close a file.
2439*/
2440static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002441 assert( id!=0 );
2442 flockUnlock(id, NO_LOCK);
2443 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002444}
2445
2446#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2447
2448/******************* End of the flock lock implementation *********************
2449******************************************************************************/
2450
2451/******************************************************************************
2452************************ Begin Named Semaphore Locking ************************
2453**
2454** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002455**
2456** Semaphore locking is like dot-lock and flock in that it really only
2457** supports EXCLUSIVE locking. Only a single process can read or write
2458** the database file at a time. This reduces potential concurrency, but
2459** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002460*/
2461#if OS_VXWORKS
2462
drh6b9d6dd2008-12-03 19:34:47 +00002463/*
2464** This routine checks if there is a RESERVED lock held on the specified
2465** file by this or any other process. If such a lock is held, set *pResOut
2466** to a non-zero value otherwise *pResOut is set to zero. The return value
2467** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2468*/
drh8cd5b252015-03-02 22:06:43 +00002469static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002470 int rc = SQLITE_OK;
2471 int reserved = 0;
2472 unixFile *pFile = (unixFile*)id;
2473
2474 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2475
2476 assert( pFile );
2477
2478 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002479 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002480 reserved = 1;
2481 }
2482
2483 /* Otherwise see if some other process holds it. */
2484 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002485 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002486
2487 if( sem_trywait(pSem)==-1 ){
2488 int tErrno = errno;
2489 if( EAGAIN != tErrno ){
2490 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002491 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002492 } else {
2493 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002494 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002495 }
2496 }else{
2497 /* we could have it if we want it */
2498 sem_post(pSem);
2499 }
2500 }
drh308c2a52010-05-14 11:30:18 +00002501 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002502
2503 *pResOut = reserved;
2504 return rc;
2505}
2506
drh6b9d6dd2008-12-03 19:34:47 +00002507/*
drh308c2a52010-05-14 11:30:18 +00002508** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002509** of the following:
2510**
2511** (1) SHARED_LOCK
2512** (2) RESERVED_LOCK
2513** (3) PENDING_LOCK
2514** (4) EXCLUSIVE_LOCK
2515**
2516** Sometimes when requesting one lock state, additional lock states
2517** are inserted in between. The locking might fail on one of the later
2518** transitions leaving the lock state different from what it started but
2519** still short of its goal. The following chart shows the allowed
2520** transitions and the inserted intermediate states:
2521**
2522** UNLOCKED -> SHARED
2523** SHARED -> RESERVED
2524** SHARED -> (PENDING) -> EXCLUSIVE
2525** RESERVED -> (PENDING) -> EXCLUSIVE
2526** PENDING -> EXCLUSIVE
2527**
2528** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2529** lock states in the sqlite3_file structure, but all locks SHARED or
2530** above are really EXCLUSIVE locks and exclude all other processes from
2531** access the file.
2532**
2533** This routine will only increase a lock. Use the sqlite3OsUnlock()
2534** routine to lower a locking level.
2535*/
drh8cd5b252015-03-02 22:06:43 +00002536static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002537 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002538 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002539 int rc = SQLITE_OK;
2540
2541 /* if we already have a lock, it is exclusive.
2542 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002543 if (pFile->eFileLock > NO_LOCK) {
2544 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002545 rc = SQLITE_OK;
2546 goto sem_end_lock;
2547 }
2548
2549 /* lock semaphore now but bail out when already locked. */
2550 if( sem_trywait(pSem)==-1 ){
2551 rc = SQLITE_BUSY;
2552 goto sem_end_lock;
2553 }
2554
2555 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002556 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002557
2558 sem_end_lock:
2559 return rc;
2560}
2561
drh6b9d6dd2008-12-03 19:34:47 +00002562/*
drh308c2a52010-05-14 11:30:18 +00002563** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002564** must be either NO_LOCK or SHARED_LOCK.
2565**
2566** If the locking level of the file descriptor is already at or below
2567** the requested locking level, this routine is a no-op.
2568*/
drh8cd5b252015-03-02 22:06:43 +00002569static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002570 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002571 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002572
2573 assert( pFile );
2574 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002575 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002576 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002577 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002578
2579 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002580 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002581 return SQLITE_OK;
2582 }
2583
2584 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002585 if (eFileLock==SHARED_LOCK) {
2586 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002587 return SQLITE_OK;
2588 }
2589
2590 /* no, really unlock. */
2591 if ( sem_post(pSem)==-1 ) {
2592 int rc, tErrno = errno;
2593 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2594 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002595 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002596 }
2597 return rc;
2598 }
drh308c2a52010-05-14 11:30:18 +00002599 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002600 return SQLITE_OK;
2601}
2602
2603/*
2604 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002605 */
drh8cd5b252015-03-02 22:06:43 +00002606static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002607 if( id ){
2608 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002609 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002610 assert( pFile );
2611 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002612 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002613 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002614 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002615 }
2616 return SQLITE_OK;
2617}
2618
2619#endif /* OS_VXWORKS */
2620/*
2621** Named semaphore locking is only available on VxWorks.
2622**
2623*************** End of the named semaphore lock implementation ****************
2624******************************************************************************/
2625
2626
2627/******************************************************************************
2628*************************** Begin AFP Locking *********************************
2629**
2630** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2631** on Apple Macintosh computers - both OS9 and OSX.
2632**
2633** Third-party implementations of AFP are available. But this code here
2634** only works on OSX.
2635*/
2636
drhd2cb50b2009-01-09 21:41:17 +00002637#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002638/*
2639** The afpLockingContext structure contains all afp lock specific state
2640*/
drhbfe66312006-10-03 17:40:40 +00002641typedef struct afpLockingContext afpLockingContext;
2642struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002643 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002644 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002645};
2646
2647struct ByteRangeLockPB2
2648{
2649 unsigned long long offset; /* offset to first byte to lock */
2650 unsigned long long length; /* nbr of bytes to lock */
2651 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2652 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2653 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2654 int fd; /* file desc to assoc this lock with */
2655};
2656
drhfd131da2007-08-07 17:13:03 +00002657#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002658
drh6b9d6dd2008-12-03 19:34:47 +00002659/*
2660** This is a utility for setting or clearing a bit-range lock on an
2661** AFP filesystem.
2662**
2663** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2664*/
2665static int afpSetLock(
2666 const char *path, /* Name of the file to be locked or unlocked */
2667 unixFile *pFile, /* Open file descriptor on path */
2668 unsigned long long offset, /* First byte to be locked */
2669 unsigned long long length, /* Number of bytes to lock */
2670 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002671){
drh6b9d6dd2008-12-03 19:34:47 +00002672 struct ByteRangeLockPB2 pb;
2673 int err;
drhbfe66312006-10-03 17:40:40 +00002674
2675 pb.unLockFlag = setLockFlag ? 0 : 1;
2676 pb.startEndFlag = 0;
2677 pb.offset = offset;
2678 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002679 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002680
drh308c2a52010-05-14 11:30:18 +00002681 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002682 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002683 offset, length));
drhbfe66312006-10-03 17:40:40 +00002684 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2685 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002686 int rc;
2687 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002688 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2689 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002690#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2691 rc = SQLITE_BUSY;
2692#else
drh734c9862008-11-28 15:37:20 +00002693 rc = sqliteErrorFromPosixError(tErrno,
2694 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002695#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002696 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002697 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002698 }
2699 return rc;
drhbfe66312006-10-03 17:40:40 +00002700 } else {
aswift5b1a2562008-08-22 00:22:35 +00002701 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002702 }
2703}
2704
drh6b9d6dd2008-12-03 19:34:47 +00002705/*
2706** This routine checks if there is a RESERVED lock held on the specified
2707** file by this or any other process. If such a lock is held, set *pResOut
2708** to a non-zero value otherwise *pResOut is set to zero. The return value
2709** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2710*/
danielk1977e339d652008-06-28 11:23:00 +00002711static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002712 int rc = SQLITE_OK;
2713 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002714 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002715 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002716
aswift5b1a2562008-08-22 00:22:35 +00002717 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2718
2719 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002720 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002721 if( context->reserved ){
2722 *pResOut = 1;
2723 return SQLITE_OK;
2724 }
drh8af6c222010-05-14 12:43:01 +00002725 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002726
2727 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002728 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002729 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002730 }
2731
2732 /* Otherwise see if some other process holds it.
2733 */
aswift5b1a2562008-08-22 00:22:35 +00002734 if( !reserved ){
2735 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002736 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002737 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002738 /* if we succeeded in taking the reserved lock, unlock it to restore
2739 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002740 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002741 } else {
2742 /* if we failed to get the lock then someone else must have it */
2743 reserved = 1;
2744 }
2745 if( IS_LOCK_ERROR(lrc) ){
2746 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002747 }
2748 }
drhbfe66312006-10-03 17:40:40 +00002749
drh7ed97b92010-01-20 13:07:21 +00002750 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002751 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002752
2753 *pResOut = reserved;
2754 return rc;
drhbfe66312006-10-03 17:40:40 +00002755}
2756
drh6b9d6dd2008-12-03 19:34:47 +00002757/*
drh308c2a52010-05-14 11:30:18 +00002758** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002759** of the following:
2760**
2761** (1) SHARED_LOCK
2762** (2) RESERVED_LOCK
2763** (3) PENDING_LOCK
2764** (4) EXCLUSIVE_LOCK
2765**
2766** Sometimes when requesting one lock state, additional lock states
2767** are inserted in between. The locking might fail on one of the later
2768** transitions leaving the lock state different from what it started but
2769** still short of its goal. The following chart shows the allowed
2770** transitions and the inserted intermediate states:
2771**
2772** UNLOCKED -> SHARED
2773** SHARED -> RESERVED
2774** SHARED -> (PENDING) -> EXCLUSIVE
2775** RESERVED -> (PENDING) -> EXCLUSIVE
2776** PENDING -> EXCLUSIVE
2777**
2778** This routine will only increase a lock. Use the sqlite3OsUnlock()
2779** routine to lower a locking level.
2780*/
drh308c2a52010-05-14 11:30:18 +00002781static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002782 int rc = SQLITE_OK;
2783 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002784 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002785 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002786
2787 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002788 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2789 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002790 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002791
drhbfe66312006-10-03 17:40:40 +00002792 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002793 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002794 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002795 */
drh308c2a52010-05-14 11:30:18 +00002796 if( pFile->eFileLock>=eFileLock ){
2797 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2798 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002799 return SQLITE_OK;
2800 }
2801
2802 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002803 ** (1) We never move from unlocked to anything higher than shared lock.
2804 ** (2) SQLite never explicitly requests a pendig lock.
2805 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002806 */
drh308c2a52010-05-14 11:30:18 +00002807 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2808 assert( eFileLock!=PENDING_LOCK );
2809 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002810
drh8af6c222010-05-14 12:43:01 +00002811 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002812 */
drh6c7d5c52008-11-21 20:32:33 +00002813 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002814 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002815
2816 /* If some thread using this PID has a lock via a different unixFile*
2817 ** handle that precludes the requested lock, return BUSY.
2818 */
drh8af6c222010-05-14 12:43:01 +00002819 if( (pFile->eFileLock!=pInode->eFileLock &&
2820 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002821 ){
2822 rc = SQLITE_BUSY;
2823 goto afp_end_lock;
2824 }
2825
2826 /* If a SHARED lock is requested, and some thread using this PID already
2827 ** has a SHARED or RESERVED lock, then increment reference counts and
2828 ** return SQLITE_OK.
2829 */
drh308c2a52010-05-14 11:30:18 +00002830 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002831 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002832 assert( eFileLock==SHARED_LOCK );
2833 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002834 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002835 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002836 pInode->nShared++;
2837 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002838 goto afp_end_lock;
2839 }
drhbfe66312006-10-03 17:40:40 +00002840
2841 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002842 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2843 ** be released.
2844 */
drh308c2a52010-05-14 11:30:18 +00002845 if( eFileLock==SHARED_LOCK
2846 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002847 ){
2848 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002849 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002850 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002851 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002852 goto afp_end_lock;
2853 }
2854 }
2855
2856 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002857 ** operating system calls for the specified lock.
2858 */
drh308c2a52010-05-14 11:30:18 +00002859 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002860 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002861 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002862
drh8af6c222010-05-14 12:43:01 +00002863 assert( pInode->nShared==0 );
2864 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002865
2866 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002867 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002868 /* note that the quality of the randomness doesn't matter that much */
2869 lk = random();
drh8af6c222010-05-14 12:43:01 +00002870 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002871 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002872 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002873 if( IS_LOCK_ERROR(lrc1) ){
2874 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002875 }
aswift5b1a2562008-08-22 00:22:35 +00002876 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002877 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002878
aswift5b1a2562008-08-22 00:22:35 +00002879 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002880 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002881 rc = lrc1;
2882 goto afp_end_lock;
2883 } else if( IS_LOCK_ERROR(lrc2) ){
2884 rc = lrc2;
2885 goto afp_end_lock;
2886 } else if( lrc1 != SQLITE_OK ) {
2887 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002888 } else {
drh308c2a52010-05-14 11:30:18 +00002889 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002890 pInode->nLock++;
2891 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002892 }
drh8af6c222010-05-14 12:43:01 +00002893 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002894 /* We are trying for an exclusive lock but another thread in this
2895 ** same process is still holding a shared lock. */
2896 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002897 }else{
2898 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2899 ** assumed that there is a SHARED or greater lock on the file
2900 ** already.
2901 */
2902 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002903 assert( 0!=pFile->eFileLock );
2904 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002905 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002906 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002907 if( !failed ){
2908 context->reserved = 1;
2909 }
drhbfe66312006-10-03 17:40:40 +00002910 }
drh308c2a52010-05-14 11:30:18 +00002911 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002912 /* Acquire an EXCLUSIVE lock */
2913
2914 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002915 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002916 */
drh6b9d6dd2008-12-03 19:34:47 +00002917 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002918 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002919 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002920 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002921 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002922 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002923 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002924 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002925 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2926 ** a critical I/O error
2927 */
drh2e233812017-08-22 15:21:54 +00002928 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00002929 SQLITE_IOERR_LOCK;
2930 goto afp_end_lock;
2931 }
2932 }else{
aswift5b1a2562008-08-22 00:22:35 +00002933 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002934 }
2935 }
aswift5b1a2562008-08-22 00:22:35 +00002936 if( failed ){
2937 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002938 }
2939 }
2940
2941 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002942 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002943 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002944 }else if( eFileLock==EXCLUSIVE_LOCK ){
2945 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002946 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002947 }
2948
2949afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002950 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002951 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2952 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002953 return rc;
2954}
2955
2956/*
drh308c2a52010-05-14 11:30:18 +00002957** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002958** must be either NO_LOCK or SHARED_LOCK.
2959**
2960** If the locking level of the file descriptor is already at or below
2961** the requested locking level, this routine is a no-op.
2962*/
drh308c2a52010-05-14 11:30:18 +00002963static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002964 int rc = SQLITE_OK;
2965 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002966 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002967 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2968 int skipShared = 0;
2969#ifdef SQLITE_TEST
2970 int h = pFile->h;
2971#endif
drhbfe66312006-10-03 17:40:40 +00002972
2973 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002974 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002975 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002976 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002977
drh308c2a52010-05-14 11:30:18 +00002978 assert( eFileLock<=SHARED_LOCK );
2979 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002980 return SQLITE_OK;
2981 }
drh6c7d5c52008-11-21 20:32:33 +00002982 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002983 pInode = pFile->pInode;
2984 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002985 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002986 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002987 SimulateIOErrorBenign(1);
2988 SimulateIOError( h=(-1) )
2989 SimulateIOErrorBenign(0);
2990
drhd3d8c042012-05-29 17:02:40 +00002991#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002992 /* When reducing a lock such that other processes can start
2993 ** reading the database file again, make sure that the
2994 ** transaction counter was updated if any part of the database
2995 ** file changed. If the transaction counter is not updated,
2996 ** other connections to the same file might not realize that
2997 ** the file has changed and hence might not know to flush their
2998 ** cache. The use of a stale cache can lead to database corruption.
2999 */
3000 assert( pFile->inNormalWrite==0
3001 || pFile->dbUpdate==0
3002 || pFile->transCntrChng==1 );
3003 pFile->inNormalWrite = 0;
3004#endif
aswiftaebf4132008-11-21 00:10:35 +00003005
drh308c2a52010-05-14 11:30:18 +00003006 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003007 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003008 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003009 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003010 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003011 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3012 } else {
3013 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003014 }
3015 }
drh308c2a52010-05-14 11:30:18 +00003016 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003017 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003018 }
drh308c2a52010-05-14 11:30:18 +00003019 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003020 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3021 if( !rc ){
3022 context->reserved = 0;
3023 }
aswiftaebf4132008-11-21 00:10:35 +00003024 }
drh8af6c222010-05-14 12:43:01 +00003025 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3026 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003027 }
aswiftaebf4132008-11-21 00:10:35 +00003028 }
drh308c2a52010-05-14 11:30:18 +00003029 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003030
drh7ed97b92010-01-20 13:07:21 +00003031 /* Decrement the shared lock counter. Release the lock using an
3032 ** OS call only when all threads in this same process have released
3033 ** the lock.
3034 */
drh8af6c222010-05-14 12:43:01 +00003035 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3036 pInode->nShared--;
3037 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003038 SimulateIOErrorBenign(1);
3039 SimulateIOError( h=(-1) )
3040 SimulateIOErrorBenign(0);
3041 if( !skipShared ){
3042 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3043 }
3044 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003045 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003046 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003047 }
3048 }
3049 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003050 pInode->nLock--;
3051 assert( pInode->nLock>=0 );
3052 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003053 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003054 }
3055 }
drhbfe66312006-10-03 17:40:40 +00003056 }
drh7ed97b92010-01-20 13:07:21 +00003057
drh6c7d5c52008-11-21 20:32:33 +00003058 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003059 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003060 return rc;
3061}
3062
3063/*
drh339eb0b2008-03-07 15:34:11 +00003064** Close a file & cleanup AFP specific locking context
3065*/
danielk1977e339d652008-06-28 11:23:00 +00003066static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003067 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003068 unixFile *pFile = (unixFile*)id;
3069 assert( id!=0 );
3070 afpUnlock(id, NO_LOCK);
3071 unixEnterMutex();
3072 if( pFile->pInode && pFile->pInode->nLock ){
3073 /* If there are outstanding locks, do not actually close the file just
3074 ** yet because that would clear those locks. Instead, add the file
3075 ** descriptor to pInode->aPending. It will be automatically closed when
3076 ** the last lock is cleared.
3077 */
3078 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003079 }
drha8de1e12015-11-30 00:05:39 +00003080 releaseInodeInfo(pFile);
3081 sqlite3_free(pFile->lockingContext);
3082 rc = closeUnixFile(id);
3083 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003084 return rc;
drhbfe66312006-10-03 17:40:40 +00003085}
3086
drhd2cb50b2009-01-09 21:41:17 +00003087#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003088/*
3089** The code above is the AFP lock implementation. The code is specific
3090** to MacOSX and does not work on other unix platforms. No alternative
3091** is available. If you don't compile for a mac, then the "unix-afp"
3092** VFS is not available.
3093**
3094********************* End of the AFP lock implementation **********************
3095******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003096
drh7ed97b92010-01-20 13:07:21 +00003097/******************************************************************************
3098*************************** Begin NFS Locking ********************************/
3099
3100#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3101/*
drh308c2a52010-05-14 11:30:18 +00003102 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003103 ** must be either NO_LOCK or SHARED_LOCK.
3104 **
3105 ** If the locking level of the file descriptor is already at or below
3106 ** the requested locking level, this routine is a no-op.
3107 */
drh308c2a52010-05-14 11:30:18 +00003108static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003109 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003110}
3111
3112#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3113/*
3114** The code above is the NFS lock implementation. The code is specific
3115** to MacOSX and does not work on other unix platforms. No alternative
3116** is available.
3117**
3118********************* End of the NFS lock implementation **********************
3119******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003120
3121/******************************************************************************
3122**************** Non-locking sqlite3_file methods *****************************
3123**
3124** The next division contains implementations for all methods of the
3125** sqlite3_file object other than the locking methods. The locking
3126** methods were defined in divisions above (one locking method per
3127** division). Those methods that are common to all locking modes
3128** are gather together into this division.
3129*/
drhbfe66312006-10-03 17:40:40 +00003130
3131/*
drh734c9862008-11-28 15:37:20 +00003132** Seek to the offset passed as the second argument, then read cnt
3133** bytes into pBuf. Return the number of bytes actually read.
3134**
3135** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3136** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3137** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003138** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003139** See tickets #2741 and #2681.
3140**
3141** To avoid stomping the errno value on a failed read the lastErrno value
3142** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003143*/
drh734c9862008-11-28 15:37:20 +00003144static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3145 int got;
drh58024642011-11-07 18:16:00 +00003146 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003147#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3148 i64 newOffset;
3149#endif
drh734c9862008-11-28 15:37:20 +00003150 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003151 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003152 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003153 do{
drh734c9862008-11-28 15:37:20 +00003154#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003155 got = osPread(id->h, pBuf, cnt, offset);
3156 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003157#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003158 got = osPread64(id->h, pBuf, cnt, offset);
3159 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003160#else
drha46cadc2016-03-04 03:02:06 +00003161 newOffset = lseek(id->h, offset, SEEK_SET);
3162 SimulateIOError( newOffset = -1 );
3163 if( newOffset<0 ){
3164 storeLastErrno((unixFile*)id, errno);
3165 return -1;
3166 }
3167 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003168#endif
drh58024642011-11-07 18:16:00 +00003169 if( got==cnt ) break;
3170 if( got<0 ){
3171 if( errno==EINTR ){ got = 1; continue; }
3172 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003173 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003174 break;
3175 }else if( got>0 ){
3176 cnt -= got;
3177 offset += got;
3178 prior += got;
3179 pBuf = (void*)(got + (char*)pBuf);
3180 }
3181 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003182 TIMER_END;
drh58024642011-11-07 18:16:00 +00003183 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3184 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3185 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003186}
3187
3188/*
drh734c9862008-11-28 15:37:20 +00003189** Read data from a file into a buffer. Return SQLITE_OK if all
3190** bytes were read successfully and SQLITE_IOERR if anything goes
3191** wrong.
drh339eb0b2008-03-07 15:34:11 +00003192*/
drh734c9862008-11-28 15:37:20 +00003193static int unixRead(
3194 sqlite3_file *id,
3195 void *pBuf,
3196 int amt,
3197 sqlite3_int64 offset
3198){
dan08da86a2009-08-21 17:18:03 +00003199 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003200 int got;
3201 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003202 assert( offset>=0 );
3203 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003204
dan08da86a2009-08-21 17:18:03 +00003205 /* If this is a database file (not a journal, master-journal or temp
3206 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003207#if 0
drhc68886b2017-08-18 16:09:52 +00003208 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003209 || offset>=PENDING_BYTE+512
3210 || offset+amt<=PENDING_BYTE
3211 );
dan7c246102010-04-12 19:00:29 +00003212#endif
drh08c6d442009-02-09 17:34:07 +00003213
drh9b4c59f2013-04-15 17:03:42 +00003214#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003215 /* Deal with as much of this read request as possible by transfering
3216 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003217 if( offset<pFile->mmapSize ){
3218 if( offset+amt <= pFile->mmapSize ){
3219 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3220 return SQLITE_OK;
3221 }else{
3222 int nCopy = pFile->mmapSize - offset;
3223 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3224 pBuf = &((u8 *)pBuf)[nCopy];
3225 amt -= nCopy;
3226 offset += nCopy;
3227 }
3228 }
drh6e0b6d52013-04-09 16:19:20 +00003229#endif
danf23da962013-03-23 21:00:41 +00003230
dan08da86a2009-08-21 17:18:03 +00003231 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003232 if( got==amt ){
3233 return SQLITE_OK;
3234 }else if( got<0 ){
3235 /* lastErrno set by seekAndRead */
3236 return SQLITE_IOERR_READ;
3237 }else{
drh4bf66fd2015-02-19 02:43:02 +00003238 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003239 /* Unread parts of the buffer must be zero-filled */
3240 memset(&((char*)pBuf)[got], 0, amt-got);
3241 return SQLITE_IOERR_SHORT_READ;
3242 }
3243}
3244
3245/*
dan47a2b4a2013-04-26 16:09:29 +00003246** Attempt to seek the file-descriptor passed as the first argument to
3247** absolute offset iOff, then attempt to write nBuf bytes of data from
3248** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3249** return the actual number of bytes written (which may be less than
3250** nBuf).
3251*/
3252static int seekAndWriteFd(
3253 int fd, /* File descriptor to write to */
3254 i64 iOff, /* File offset to begin writing at */
3255 const void *pBuf, /* Copy data from this buffer to the file */
3256 int nBuf, /* Size of buffer pBuf in bytes */
3257 int *piErrno /* OUT: Error number if error occurs */
3258){
3259 int rc = 0; /* Value returned by system call */
3260
3261 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003262 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003263 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003264 nBuf &= 0x1ffff;
3265 TIMER_START;
3266
3267#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003268 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003269#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003270 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003271#else
3272 do{
3273 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003274 SimulateIOError( iSeek = -1 );
3275 if( iSeek<0 ){
3276 rc = -1;
3277 break;
dan47a2b4a2013-04-26 16:09:29 +00003278 }
3279 rc = osWrite(fd, pBuf, nBuf);
3280 }while( rc<0 && errno==EINTR );
3281#endif
3282
3283 TIMER_END;
3284 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3285
drhe1818ec2015-12-01 16:21:35 +00003286 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003287 return rc;
3288}
3289
3290
3291/*
drh734c9862008-11-28 15:37:20 +00003292** Seek to the offset in id->offset then read cnt bytes into pBuf.
3293** Return the number of bytes actually read. Update the offset.
3294**
3295** To avoid stomping the errno value on a failed write the lastErrno value
3296** is set before returning.
3297*/
3298static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003299 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003300}
3301
3302
3303/*
3304** Write data from a buffer into a file. Return SQLITE_OK on success
3305** or some other error code on failure.
3306*/
3307static int unixWrite(
3308 sqlite3_file *id,
3309 const void *pBuf,
3310 int amt,
3311 sqlite3_int64 offset
3312){
dan08da86a2009-08-21 17:18:03 +00003313 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003314 int wrote = 0;
3315 assert( id );
3316 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003317
dan08da86a2009-08-21 17:18:03 +00003318 /* If this is a database file (not a journal, master-journal or temp
3319 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003320#if 0
drhc68886b2017-08-18 16:09:52 +00003321 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003322 || offset>=PENDING_BYTE+512
3323 || offset+amt<=PENDING_BYTE
3324 );
dan7c246102010-04-12 19:00:29 +00003325#endif
drh08c6d442009-02-09 17:34:07 +00003326
drhd3d8c042012-05-29 17:02:40 +00003327#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003328 /* If we are doing a normal write to a database file (as opposed to
3329 ** doing a hot-journal rollback or a write to some file other than a
3330 ** normal database file) then record the fact that the database
3331 ** has changed. If the transaction counter is modified, record that
3332 ** fact too.
3333 */
dan08da86a2009-08-21 17:18:03 +00003334 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003335 pFile->dbUpdate = 1; /* The database has been modified */
3336 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003337 int rc;
drh8f941bc2009-01-14 23:03:40 +00003338 char oldCntr[4];
3339 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003340 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003341 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003342 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003343 pFile->transCntrChng = 1; /* The transaction counter has changed */
3344 }
3345 }
3346 }
3347#endif
3348
danfe33e392015-11-17 20:56:06 +00003349#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003350 /* Deal with as much of this write request as possible by transfering
3351 ** data from the memory mapping using memcpy(). */
3352 if( offset<pFile->mmapSize ){
3353 if( offset+amt <= pFile->mmapSize ){
3354 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3355 return SQLITE_OK;
3356 }else{
3357 int nCopy = pFile->mmapSize - offset;
3358 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3359 pBuf = &((u8 *)pBuf)[nCopy];
3360 amt -= nCopy;
3361 offset += nCopy;
3362 }
3363 }
drh6e0b6d52013-04-09 16:19:20 +00003364#endif
drh02bf8b42015-09-01 23:51:53 +00003365
3366 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003367 amt -= wrote;
3368 offset += wrote;
3369 pBuf = &((char*)pBuf)[wrote];
3370 }
3371 SimulateIOError(( wrote=(-1), amt=1 ));
3372 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003373
drh02bf8b42015-09-01 23:51:53 +00003374 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003375 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003376 /* lastErrno set by seekAndWrite */
3377 return SQLITE_IOERR_WRITE;
3378 }else{
drh4bf66fd2015-02-19 02:43:02 +00003379 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003380 return SQLITE_FULL;
3381 }
3382 }
dan6e09d692010-07-27 18:34:15 +00003383
drh734c9862008-11-28 15:37:20 +00003384 return SQLITE_OK;
3385}
3386
3387#ifdef SQLITE_TEST
3388/*
3389** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003390** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003391*/
3392int sqlite3_sync_count = 0;
3393int sqlite3_fullsync_count = 0;
3394#endif
3395
3396/*
drh89240432009-03-25 01:06:01 +00003397** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003398** Others do no. To be safe, we will stick with the (slightly slower)
3399** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003400** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003401*/
drhf7a4a1b2015-01-10 18:02:45 +00003402#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003403# define fdatasync fsync
3404#endif
3405
3406/*
3407** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3408** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3409** only available on Mac OS X. But that could change.
3410*/
3411#ifdef F_FULLFSYNC
3412# define HAVE_FULLFSYNC 1
3413#else
3414# define HAVE_FULLFSYNC 0
3415#endif
3416
3417
3418/*
3419** The fsync() system call does not work as advertised on many
3420** unix systems. The following procedure is an attempt to make
3421** it work better.
3422**
3423** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3424** for testing when we want to run through the test suite quickly.
3425** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3426** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3427** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003428**
3429** SQLite sets the dataOnly flag if the size of the file is unchanged.
3430** The idea behind dataOnly is that it should only write the file content
3431** to disk, not the inode. We only set dataOnly if the file size is
3432** unchanged since the file size is part of the inode. However,
3433** Ted Ts'o tells us that fdatasync() will also write the inode if the
3434** file size has changed. The only real difference between fdatasync()
3435** and fsync(), Ted tells us, is that fdatasync() will not flush the
3436** inode if the mtime or owner or other inode attributes have changed.
3437** We only care about the file size, not the other file attributes, so
3438** as far as SQLite is concerned, an fdatasync() is always adequate.
3439** So, we always use fdatasync() if it is available, regardless of
3440** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003441*/
3442static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003443 int rc;
drh734c9862008-11-28 15:37:20 +00003444
3445 /* The following "ifdef/elif/else/" block has the same structure as
3446 ** the one below. It is replicated here solely to avoid cluttering
3447 ** up the real code with the UNUSED_PARAMETER() macros.
3448 */
3449#ifdef SQLITE_NO_SYNC
3450 UNUSED_PARAMETER(fd);
3451 UNUSED_PARAMETER(fullSync);
3452 UNUSED_PARAMETER(dataOnly);
3453#elif HAVE_FULLFSYNC
3454 UNUSED_PARAMETER(dataOnly);
3455#else
3456 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003457 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003458#endif
3459
3460 /* Record the number of times that we do a normal fsync() and
3461 ** FULLSYNC. This is used during testing to verify that this procedure
3462 ** gets called with the correct arguments.
3463 */
3464#ifdef SQLITE_TEST
3465 if( fullSync ) sqlite3_fullsync_count++;
3466 sqlite3_sync_count++;
3467#endif
3468
3469 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003470 ** no-op. But go ahead and call fstat() to validate the file
3471 ** descriptor as we need a method to provoke a failure during
3472 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003473 */
3474#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003475 {
3476 struct stat buf;
3477 rc = osFstat(fd, &buf);
3478 }
drh734c9862008-11-28 15:37:20 +00003479#elif HAVE_FULLFSYNC
3480 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003481 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003482 }else{
3483 rc = 1;
3484 }
3485 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003486 ** It shouldn't be possible for fullfsync to fail on the local
3487 ** file system (on OSX), so failure indicates that FULLFSYNC
3488 ** isn't supported for this file system. So, attempt an fsync
3489 ** and (for now) ignore the overhead of a superfluous fcntl call.
3490 ** It'd be better to detect fullfsync support once and avoid
3491 ** the fcntl call every time sync is called.
3492 */
drh734c9862008-11-28 15:37:20 +00003493 if( rc ) rc = fsync(fd);
3494
drh7ed97b92010-01-20 13:07:21 +00003495#elif defined(__APPLE__)
3496 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3497 ** so currently we default to the macro that redefines fdatasync to fsync
3498 */
3499 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003500#else
drh0b647ff2009-03-21 14:41:04 +00003501 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003502#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003503 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003504 rc = fsync(fd);
3505 }
drh0b647ff2009-03-21 14:41:04 +00003506#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003507#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3508
3509 if( OS_VXWORKS && rc!= -1 ){
3510 rc = 0;
3511 }
chw97185482008-11-17 08:05:31 +00003512 return rc;
drhbfe66312006-10-03 17:40:40 +00003513}
3514
drh734c9862008-11-28 15:37:20 +00003515/*
drh0059eae2011-08-08 23:48:40 +00003516** Open a file descriptor to the directory containing file zFilename.
3517** If successful, *pFd is set to the opened file descriptor and
3518** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3519** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3520** value.
3521**
drh90315a22011-08-10 01:52:12 +00003522** The directory file descriptor is used for only one thing - to
3523** fsync() a directory to make sure file creation and deletion events
3524** are flushed to disk. Such fsyncs are not needed on newer
3525** journaling filesystems, but are required on older filesystems.
3526**
3527** This routine can be overridden using the xSetSysCall interface.
3528** The ability to override this routine was added in support of the
3529** chromium sandbox. Opening a directory is a security risk (we are
3530** told) so making it overrideable allows the chromium sandbox to
3531** replace this routine with a harmless no-op. To make this routine
3532** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3533** *pFd set to a negative number.
3534**
drh0059eae2011-08-08 23:48:40 +00003535** If SQLITE_OK is returned, the caller is responsible for closing
3536** the file descriptor *pFd using close().
3537*/
3538static int openDirectory(const char *zFilename, int *pFd){
3539 int ii;
3540 int fd = -1;
3541 char zDirname[MAX_PATHNAME+1];
3542
3543 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003544 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3545 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003546 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003547 }else{
3548 if( zDirname[0]!='/' ) zDirname[0] = '.';
3549 zDirname[1] = 0;
3550 }
3551 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3552 if( fd>=0 ){
3553 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003554 }
3555 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003556 if( fd>=0 ) return SQLITE_OK;
3557 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003558}
3559
3560/*
drh734c9862008-11-28 15:37:20 +00003561** Make sure all writes to a particular file are committed to disk.
3562**
3563** If dataOnly==0 then both the file itself and its metadata (file
3564** size, access time, etc) are synced. If dataOnly!=0 then only the
3565** file data is synced.
3566**
3567** Under Unix, also make sure that the directory entry for the file
3568** has been created by fsync-ing the directory that contains the file.
3569** If we do not do this and we encounter a power failure, the directory
3570** entry for the journal might not exist after we reboot. The next
3571** SQLite to access the file will not know that the journal exists (because
3572** the directory entry for the journal was never created) and the transaction
3573** will not roll back - possibly leading to database corruption.
3574*/
3575static int unixSync(sqlite3_file *id, int flags){
3576 int rc;
3577 unixFile *pFile = (unixFile*)id;
3578
3579 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3580 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3581
3582 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3583 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3584 || (flags&0x0F)==SQLITE_SYNC_FULL
3585 );
3586
3587 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3588 ** line is to test that doing so does not cause any problems.
3589 */
3590 SimulateDiskfullError( return SQLITE_FULL );
3591
3592 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003593 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003594 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3595 SimulateIOError( rc=1 );
3596 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003597 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003598 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003599 }
drh0059eae2011-08-08 23:48:40 +00003600
3601 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003602 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003603 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003604 */
3605 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3606 int dirfd;
3607 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003608 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003609 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003610 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003611 full_fsync(dirfd, 0, 0);
3612 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003613 }else{
3614 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003615 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003616 }
drh0059eae2011-08-08 23:48:40 +00003617 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003618 }
3619 return rc;
3620}
3621
3622/*
3623** Truncate an open file to a specified size
3624*/
3625static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003626 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003627 int rc;
dan6e09d692010-07-27 18:34:15 +00003628 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003629 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003630
3631 /* If the user has configured a chunk-size for this file, truncate the
3632 ** file so that it consists of an integer number of chunks (i.e. the
3633 ** actual file size after the operation may be larger than the requested
3634 ** size).
3635 */
drhb8af4b72012-04-05 20:04:39 +00003636 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003637 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3638 }
3639
dan2ee53412014-09-06 16:49:40 +00003640 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003641 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003642 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003643 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003644 }else{
drhd3d8c042012-05-29 17:02:40 +00003645#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003646 /* If we are doing a normal write to a database file (as opposed to
3647 ** doing a hot-journal rollback or a write to some file other than a
3648 ** normal database file) and we truncate the file to zero length,
3649 ** that effectively updates the change counter. This might happen
3650 ** when restoring a database using the backup API from a zero-length
3651 ** source.
3652 */
dan6e09d692010-07-27 18:34:15 +00003653 if( pFile->inNormalWrite && nByte==0 ){
3654 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003655 }
danf23da962013-03-23 21:00:41 +00003656#endif
danc0003312013-03-22 17:46:11 +00003657
mistachkine98844f2013-08-24 00:59:24 +00003658#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003659 /* If the file was just truncated to a size smaller than the currently
3660 ** mapped region, reduce the effective mapping size as well. SQLite will
3661 ** use read() and write() to access data beyond this point from now on.
3662 */
3663 if( nByte<pFile->mmapSize ){
3664 pFile->mmapSize = nByte;
3665 }
mistachkine98844f2013-08-24 00:59:24 +00003666#endif
drh3313b142009-11-06 04:13:18 +00003667
drh734c9862008-11-28 15:37:20 +00003668 return SQLITE_OK;
3669 }
3670}
3671
3672/*
3673** Determine the current size of a file in bytes
3674*/
3675static int unixFileSize(sqlite3_file *id, i64 *pSize){
3676 int rc;
3677 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003678 assert( id );
3679 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003680 SimulateIOError( rc=1 );
3681 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003682 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003683 return SQLITE_IOERR_FSTAT;
3684 }
3685 *pSize = buf.st_size;
3686
drh8af6c222010-05-14 12:43:01 +00003687 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003688 ** writes a single byte into that file in order to work around a bug
3689 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3690 ** layers, we need to report this file size as zero even though it is
3691 ** really 1. Ticket #3260.
3692 */
3693 if( *pSize==1 ) *pSize = 0;
3694
3695
3696 return SQLITE_OK;
3697}
3698
drhd2cb50b2009-01-09 21:41:17 +00003699#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003700/*
3701** Handler for proxy-locking file-control verbs. Defined below in the
3702** proxying locking division.
3703*/
3704static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003705#endif
drh715ff302008-12-03 22:32:44 +00003706
dan502019c2010-07-28 14:26:17 +00003707/*
3708** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003709** file-control operation. Enlarge the database to nBytes in size
3710** (rounded up to the next chunk-size). If the database is already
3711** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003712*/
3713static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003714 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003715 i64 nSize; /* Required file size */
3716 struct stat buf; /* Used to hold return values of fstat() */
3717
drh4bf66fd2015-02-19 02:43:02 +00003718 if( osFstat(pFile->h, &buf) ){
3719 return SQLITE_IOERR_FSTAT;
3720 }
dan502019c2010-07-28 14:26:17 +00003721
3722 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3723 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003724
dan502019c2010-07-28 14:26:17 +00003725#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003726 /* The code below is handling the return value of osFallocate()
3727 ** correctly. posix_fallocate() is defined to "returns zero on success,
3728 ** or an error number on failure". See the manpage for details. */
3729 int err;
drhff812312011-02-23 13:33:46 +00003730 do{
dan661d71a2011-03-30 19:08:03 +00003731 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3732 }while( err==EINTR );
3733 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003734#else
dan592bf7f2014-12-30 19:58:31 +00003735 /* If the OS does not have posix_fallocate(), fake it. Write a
3736 ** single byte to the last byte in each block that falls entirely
3737 ** within the extended region. Then, if required, a single byte
3738 ** at offset (nSize-1), to set the size of the file correctly.
3739 ** This is a similar technique to that used by glibc on systems
3740 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003741 */
3742 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003743 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003744 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003745
drh053378d2015-12-01 22:09:42 +00003746 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003747 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003748 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003749 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3750 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003751 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003752 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003753 }
dan502019c2010-07-28 14:26:17 +00003754#endif
3755 }
3756 }
3757
mistachkine98844f2013-08-24 00:59:24 +00003758#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003759 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003760 int rc;
3761 if( pFile->szChunk<=0 ){
3762 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003763 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003764 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3765 }
3766 }
3767
3768 rc = unixMapfile(pFile, nByte);
3769 return rc;
3770 }
mistachkine98844f2013-08-24 00:59:24 +00003771#endif
danf23da962013-03-23 21:00:41 +00003772
dan502019c2010-07-28 14:26:17 +00003773 return SQLITE_OK;
3774}
danielk1977ad94b582007-08-20 06:44:22 +00003775
danielk1977e3026632004-06-22 11:29:02 +00003776/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003777** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003778** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3779**
3780** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3781*/
3782static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3783 if( *pArg<0 ){
3784 *pArg = (pFile->ctrlFlags & mask)!=0;
3785 }else if( (*pArg)==0 ){
3786 pFile->ctrlFlags &= ~mask;
3787 }else{
3788 pFile->ctrlFlags |= mask;
3789 }
3790}
3791
drh696b33e2012-12-06 19:01:42 +00003792/* Forward declaration */
3793static int unixGetTempname(int nBuf, char *zBuf);
3794
drhf12b3f62011-12-21 14:42:29 +00003795/*
drh9e33c2c2007-08-31 18:34:59 +00003796** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003797*/
drhcc6bb3e2007-08-31 16:11:35 +00003798static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003799 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003800 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003801#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003802 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3803 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003804 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003805 }
3806 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3807 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003808 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003809 }
3810 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3811 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003812 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003813 }
drhd76dba72017-07-22 16:00:34 +00003814#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003815
drh9e33c2c2007-08-31 18:34:59 +00003816 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003817 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003818 return SQLITE_OK;
3819 }
drh4bf66fd2015-02-19 02:43:02 +00003820 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003821 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003822 return SQLITE_OK;
3823 }
dan6e09d692010-07-27 18:34:15 +00003824 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003825 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003826 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003827 }
drh9ff27ec2010-05-19 19:26:05 +00003828 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003829 int rc;
3830 SimulateIOErrorBenign(1);
3831 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3832 SimulateIOErrorBenign(0);
3833 return rc;
drhf0b190d2011-07-26 16:03:07 +00003834 }
3835 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003836 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3837 return SQLITE_OK;
3838 }
drhcb15f352011-12-23 01:04:17 +00003839 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3840 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003841 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003842 }
drhde60fc22011-12-14 17:53:36 +00003843 case SQLITE_FCNTL_VFSNAME: {
3844 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3845 return SQLITE_OK;
3846 }
drh696b33e2012-12-06 19:01:42 +00003847 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003848 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003849 if( zTFile ){
3850 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3851 *(char**)pArg = zTFile;
3852 }
3853 return SQLITE_OK;
3854 }
drhb959a012013-12-07 12:29:22 +00003855 case SQLITE_FCNTL_HAS_MOVED: {
3856 *(int*)pArg = fileHasMoved(pFile);
3857 return SQLITE_OK;
3858 }
mistachkine98844f2013-08-24 00:59:24 +00003859#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003860 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003861 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003862 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003863 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3864 newLimit = sqlite3GlobalConfig.mxMmap;
3865 }
dan43c1e622017-08-07 18:13:28 +00003866
3867 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00003868 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3869 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00003870 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00003871 newLimit = (newLimit & 0x7FFFFFFF);
3872 }
3873
drh9b4c59f2013-04-15 17:03:42 +00003874 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003875 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003876 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003877 if( pFile->mmapSize>0 ){
3878 unixUnmapfile(pFile);
3879 rc = unixMapfile(pFile, -1);
3880 }
danbcb8a862013-04-08 15:30:41 +00003881 }
drh34e258c2013-05-23 01:40:53 +00003882 return rc;
danb2d3de32013-03-14 18:34:37 +00003883 }
mistachkine98844f2013-08-24 00:59:24 +00003884#endif
drhd3d8c042012-05-29 17:02:40 +00003885#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003886 /* The pager calls this method to signal that it has done
3887 ** a rollback and that the database is therefore unchanged and
3888 ** it hence it is OK for the transaction change counter to be
3889 ** unchanged.
3890 */
3891 case SQLITE_FCNTL_DB_UNCHANGED: {
3892 ((unixFile*)id)->dbUpdate = 0;
3893 return SQLITE_OK;
3894 }
3895#endif
drhd2cb50b2009-01-09 21:41:17 +00003896#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003897 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3898 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003899 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003900 }
drhd2cb50b2009-01-09 21:41:17 +00003901#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003902 }
drh0b52b7d2011-01-26 19:46:22 +00003903 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003904}
3905
3906/*
danefe16972017-07-20 19:49:14 +00003907** If pFd->sectorSize is non-zero when this function is called, it is a
3908** no-op. Otherwise, the values of pFd->sectorSize and
3909** pFd->deviceCharacteristics are set according to the file-system
3910** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00003911**
danefe16972017-07-20 19:49:14 +00003912** There are two versions of this function. One for QNX and one for all
3913** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00003914*/
danefe16972017-07-20 19:49:14 +00003915#ifndef __QNXNTO__
3916static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00003917 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00003918 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00003919#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003920 int res;
dan9d709542017-07-21 21:06:24 +00003921 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00003922
danefe16972017-07-20 19:49:14 +00003923 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00003924 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
3925 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00003926 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00003927 }
drhd76dba72017-07-22 16:00:34 +00003928#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003929
3930 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3931 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3932 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3933 }
3934
3935 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3936 }
3937}
3938#else
drh537dddf2012-10-26 13:46:24 +00003939#include <sys/dcmd_blk.h>
3940#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00003941static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00003942 if( pFile->sectorSize == 0 ){
3943 struct statvfs fsInfo;
3944
3945 /* Set defaults for non-supported filesystems */
3946 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3947 pFile->deviceCharacteristics = 0;
3948 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3949 return pFile->sectorSize;
3950 }
3951
3952 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3953 pFile->sectorSize = fsInfo.f_bsize;
3954 pFile->deviceCharacteristics =
3955 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3956 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3957 ** the write succeeds */
3958 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3959 ** so it is ordered */
3960 0;
3961 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3962 pFile->sectorSize = fsInfo.f_bsize;
3963 pFile->deviceCharacteristics =
3964 /* etfs cluster size writes are atomic */
3965 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3966 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3967 ** the write succeeds */
3968 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3969 ** so it is ordered */
3970 0;
3971 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3972 pFile->sectorSize = fsInfo.f_bsize;
3973 pFile->deviceCharacteristics =
3974 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3975 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3976 ** the write succeeds */
3977 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3978 ** so it is ordered */
3979 0;
3980 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3981 pFile->sectorSize = fsInfo.f_bsize;
3982 pFile->deviceCharacteristics =
3983 /* full bitset of atomics from max sector size and smaller */
3984 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3985 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3986 ** so it is ordered */
3987 0;
3988 }else if( strstr(fsInfo.f_basetype, "dos") ){
3989 pFile->sectorSize = fsInfo.f_bsize;
3990 pFile->deviceCharacteristics =
3991 /* full bitset of atomics from max sector size and smaller */
3992 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3993 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3994 ** so it is ordered */
3995 0;
3996 }else{
3997 pFile->deviceCharacteristics =
3998 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3999 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4000 ** the write succeeds */
4001 0;
4002 }
4003 }
4004 /* Last chance verification. If the sector size isn't a multiple of 512
4005 ** then it isn't valid.*/
4006 if( pFile->sectorSize % 512 != 0 ){
4007 pFile->deviceCharacteristics = 0;
4008 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4009 }
drh537dddf2012-10-26 13:46:24 +00004010}
danefe16972017-07-20 19:49:14 +00004011#endif
4012
4013/*
4014** Return the sector size in bytes of the underlying block device for
4015** the specified file. This is almost always 512 bytes, but may be
4016** larger for some devices.
4017**
4018** SQLite code assumes this function cannot fail. It also assumes that
4019** if two files are created in the same file-system directory (i.e.
4020** a database and its journal file) that the sector size will be the
4021** same for both.
4022*/
4023static int unixSectorSize(sqlite3_file *id){
4024 unixFile *pFd = (unixFile*)id;
4025 setDeviceCharacteristics(pFd);
4026 return pFd->sectorSize;
4027}
danielk1977a3d4c882007-03-23 10:08:38 +00004028
danielk197790949c22007-08-17 16:50:38 +00004029/*
drhf12b3f62011-12-21 14:42:29 +00004030** Return the device characteristics for the file.
4031**
drhcb15f352011-12-23 01:04:17 +00004032** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004033** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004034** file system does not always provide powersafe overwrites. (In other
4035** words, after a power-loss event, parts of the file that were never
4036** written might end up being altered.) However, non-PSOW behavior is very,
4037** very rare. And asserting PSOW makes a large reduction in the amount
4038** of required I/O for journaling, since a lot of padding is eliminated.
4039** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4040** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004041*/
drhf12b3f62011-12-21 14:42:29 +00004042static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004043 unixFile *pFd = (unixFile*)id;
4044 setDeviceCharacteristics(pFd);
4045 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004046}
4047
dan702eec12014-06-23 10:04:58 +00004048#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004049
dan702eec12014-06-23 10:04:58 +00004050/*
4051** Return the system page size.
4052**
4053** This function should not be called directly by other code in this file.
4054** Instead, it should be called via macro osGetpagesize().
4055*/
4056static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004057#if OS_VXWORKS
4058 return 1024;
4059#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004060 return getpagesize();
4061#else
4062 return (int)sysconf(_SC_PAGESIZE);
4063#endif
4064}
4065
4066#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4067
4068#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004069
4070/*
drhd91c68f2010-05-14 14:52:25 +00004071** Object used to represent an shared memory buffer.
4072**
4073** When multiple threads all reference the same wal-index, each thread
4074** has its own unixShm object, but they all point to a single instance
4075** of this unixShmNode object. In other words, each wal-index is opened
4076** only once per process.
4077**
4078** Each unixShmNode object is connected to a single unixInodeInfo object.
4079** We could coalesce this object into unixInodeInfo, but that would mean
4080** every open file that does not use shared memory (in other words, most
4081** open files) would have to carry around this extra information. So
4082** the unixInodeInfo object contains a pointer to this unixShmNode object
4083** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004084**
4085** unixMutexHeld() must be true when creating or destroying
4086** this object or while reading or writing the following fields:
4087**
4088** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004089**
4090** The following fields are read-only after the object is created:
4091**
4092** fid
4093** zFilename
4094**
drhd91c68f2010-05-14 14:52:25 +00004095** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004096** unixMutexHeld() is true when reading or writing any other field
4097** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004098*/
drhd91c68f2010-05-14 14:52:25 +00004099struct unixShmNode {
4100 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004101 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004102 char *zFilename; /* Name of the mmapped file */
4103 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004104 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004105 u16 nRegion; /* Size of array apRegion */
4106 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004107 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004108 int nRef; /* Number of unixShm objects pointing to this */
4109 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004110#ifdef SQLITE_DEBUG
4111 u8 exclMask; /* Mask of exclusive locks held */
4112 u8 sharedMask; /* Mask of shared locks held */
4113 u8 nextShmId; /* Next available unixShm.id value */
4114#endif
4115};
4116
4117/*
drhd9e5c4f2010-05-12 18:01:39 +00004118** Structure used internally by this VFS to record the state of an
4119** open shared memory connection.
4120**
drhd91c68f2010-05-14 14:52:25 +00004121** The following fields are initialized when this object is created and
4122** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004123**
drhd91c68f2010-05-14 14:52:25 +00004124** unixShm.pFile
4125** unixShm.id
4126**
4127** All other fields are read/write. The unixShm.pFile->mutex must be held
4128** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004129*/
4130struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004131 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4132 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004133 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004134 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004135 u16 sharedMask; /* Mask of shared locks held */
4136 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004137};
4138
4139/*
drhd9e5c4f2010-05-12 18:01:39 +00004140** Constants used for locking
4141*/
drhbd9676c2010-06-23 17:58:38 +00004142#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004143#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004144
drhd9e5c4f2010-05-12 18:01:39 +00004145/*
drh73b64e42010-05-30 19:55:15 +00004146** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004147**
4148** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4149** otherwise.
4150*/
4151static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004152 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004153 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004154 int ofst, /* First byte of the locking range */
4155 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004156){
drhbbf76ee2015-03-10 20:22:35 +00004157 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4158 struct flock f; /* The posix advisory locking structure */
4159 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004160
drhd91c68f2010-05-14 14:52:25 +00004161 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004162 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004163 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004164
drh73b64e42010-05-30 19:55:15 +00004165 /* Shared locks never span more than one byte */
4166 assert( n==1 || lockType!=F_RDLCK );
4167
4168 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004169 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004170
drh3cb93392011-03-12 18:10:44 +00004171 if( pShmNode->h>=0 ){
4172 /* Initialize the locking parameters */
4173 memset(&f, 0, sizeof(f));
4174 f.l_type = lockType;
4175 f.l_whence = SEEK_SET;
4176 f.l_start = ofst;
4177 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004178
drhdcfb9652015-12-02 00:05:26 +00004179 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004180 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4181 }
drhd9e5c4f2010-05-12 18:01:39 +00004182
4183 /* Update the global lock state and do debug tracing */
4184#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004185 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004186 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004187 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004188 if( rc==SQLITE_OK ){
4189 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004190 OSTRACE(("unlock %d ok", ofst));
4191 pShmNode->exclMask &= ~mask;
4192 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004193 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004194 OSTRACE(("read-lock %d ok", ofst));
4195 pShmNode->exclMask &= ~mask;
4196 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004197 }else{
4198 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004199 OSTRACE(("write-lock %d ok", ofst));
4200 pShmNode->exclMask |= mask;
4201 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004202 }
4203 }else{
4204 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004205 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004206 }else if( lockType==F_RDLCK ){
4207 OSTRACE(("read-lock failed"));
4208 }else{
4209 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004210 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004211 }
4212 }
drh20e1f082010-05-31 16:10:12 +00004213 OSTRACE((" - afterwards %03x,%03x\n",
4214 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004215 }
drhd9e5c4f2010-05-12 18:01:39 +00004216#endif
4217
4218 return rc;
4219}
4220
dan781e34c2014-03-20 08:59:47 +00004221/*
dan781e34c2014-03-20 08:59:47 +00004222** Return the minimum number of 32KB shm regions that should be mapped at
4223** a time, assuming that each mapping must be an integer multiple of the
4224** current system page-size.
4225**
4226** Usually, this is 1. The exception seems to be systems that are configured
4227** to use 64KB pages - in this case each mapping must cover at least two
4228** shm regions.
4229*/
4230static int unixShmRegionPerMap(void){
4231 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004232 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004233 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4234 if( pgsz<shmsz ) return 1;
4235 return pgsz/shmsz;
4236}
drhd9e5c4f2010-05-12 18:01:39 +00004237
4238/*
drhd91c68f2010-05-14 14:52:25 +00004239** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004240**
4241** This is not a VFS shared-memory method; it is a utility function called
4242** by VFS shared-memory methods.
4243*/
drhd91c68f2010-05-14 14:52:25 +00004244static void unixShmPurge(unixFile *pFd){
4245 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004246 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004247 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004248 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004249 int i;
drhd91c68f2010-05-14 14:52:25 +00004250 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004251 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004252 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004253 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004254 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004255 }else{
4256 sqlite3_free(p->apRegion[i]);
4257 }
dan13a3cb82010-06-11 19:04:21 +00004258 }
dan18801912010-06-14 14:07:50 +00004259 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004260 if( p->h>=0 ){
4261 robust_close(pFd, p->h, __LINE__);
4262 p->h = -1;
4263 }
drhd91c68f2010-05-14 14:52:25 +00004264 p->pInode->pShmNode = 0;
4265 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004266 }
4267}
4268
4269/*
danda9fe0c2010-07-13 18:44:03 +00004270** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004271** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004272**
drh7234c6d2010-06-19 15:10:09 +00004273** The file used to implement shared-memory is in the same directory
4274** as the open database file and has the same name as the open database
4275** file with the "-shm" suffix added. For example, if the database file
4276** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004277** for shared memory will be called "/home/user1/config.db-shm".
4278**
4279** Another approach to is to use files in /dev/shm or /dev/tmp or an
4280** some other tmpfs mount. But if a file in a different directory
4281** from the database file is used, then differing access permissions
4282** or a chroot() might cause two different processes on the same
4283** database to end up using different files for shared memory -
4284** meaning that their memory would not really be shared - resulting
4285** in database corruption. Nevertheless, this tmpfs file usage
4286** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4287** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4288** option results in an incompatible build of SQLite; builds of SQLite
4289** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4290** same database file at the same time, database corruption will likely
4291** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4292** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004293**
4294** When opening a new shared-memory file, if no other instances of that
4295** file are currently open, in this process or in other processes, then
4296** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004297**
4298** If the original database file (pDbFd) is using the "unix-excl" VFS
4299** that means that an exclusive lock is held on the database file and
4300** that no other processes are able to read or write the database. In
4301** that case, we do not really need shared memory. No shared memory
4302** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004303*/
danda9fe0c2010-07-13 18:44:03 +00004304static int unixOpenSharedMemory(unixFile *pDbFd){
4305 struct unixShm *p = 0; /* The connection to be opened */
4306 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4307 int rc; /* Result code */
4308 unixInodeInfo *pInode; /* The inode of fd */
4309 char *zShmFilename; /* Name of the file used for SHM */
4310 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004311
danda9fe0c2010-07-13 18:44:03 +00004312 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004313 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004314 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004315 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004316 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004317
danda9fe0c2010-07-13 18:44:03 +00004318 /* Check to see if a unixShmNode object already exists. Reuse an existing
4319 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004320 */
4321 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004322 pInode = pDbFd->pInode;
4323 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004324 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004325 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004326#ifndef SQLITE_SHM_DIRECTORY
4327 const char *zBasePath = pDbFd->zPath;
4328#endif
danddb0ac42010-07-14 14:48:58 +00004329
4330 /* Call fstat() to figure out the permissions on the database file. If
4331 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004332 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004333 */
drhf3b1ed02015-12-02 13:11:03 +00004334 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004335 rc = SQLITE_IOERR_FSTAT;
4336 goto shm_open_err;
4337 }
4338
drha4ced192010-07-15 18:32:40 +00004339#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004340 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004341#else
drh4bf66fd2015-02-19 02:43:02 +00004342 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004343#endif
drhf3cdcdc2015-04-29 16:50:28 +00004344 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004345 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004346 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004347 goto shm_open_err;
4348 }
drh9cb5a0d2012-01-05 21:19:54 +00004349 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004350 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004351#ifdef SQLITE_SHM_DIRECTORY
4352 sqlite3_snprintf(nShmFilename, zShmFilename,
4353 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4354 (u32)sStat.st_ino, (u32)sStat.st_dev);
4355#else
drh4bf66fd2015-02-19 02:43:02 +00004356 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004357 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004358#endif
drhd91c68f2010-05-14 14:52:25 +00004359 pShmNode->h = -1;
4360 pDbFd->pInode->pShmNode = pShmNode;
4361 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004362 if( sqlite3GlobalConfig.bCoreMutex ){
4363 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4364 if( pShmNode->mutex==0 ){
4365 rc = SQLITE_NOMEM_BKPT;
4366 goto shm_open_err;
4367 }
drhd91c68f2010-05-14 14:52:25 +00004368 }
drhd9e5c4f2010-05-12 18:01:39 +00004369
drh3cb93392011-03-12 18:10:44 +00004370 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004371 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004372 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004373 openFlags = O_RDONLY;
4374 pShmNode->isReadonly = 1;
4375 }
4376 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004377 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004378 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4379 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004380 }
drhac7c3ac2012-02-11 19:23:48 +00004381
4382 /* If this process is running as root, make sure that the SHM file
4383 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004384 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004385 */
drh6226ca22015-11-24 15:06:28 +00004386 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004387
4388 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004389 ** If not, truncate the file to zero length.
4390 */
4391 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004392 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004393 if( robust_ftruncate(pShmNode->h, 0) ){
4394 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004395 }
4396 }
drh66dfec8b2011-06-01 20:01:49 +00004397 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004398 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004399 }
4400 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004401 }
drhd9e5c4f2010-05-12 18:01:39 +00004402 }
4403
drhd91c68f2010-05-14 14:52:25 +00004404 /* Make the new connection a child of the unixShmNode */
4405 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004406#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004407 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004408#endif
drhd91c68f2010-05-14 14:52:25 +00004409 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004410 pDbFd->pShm = p;
4411 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004412
4413 /* The reference count on pShmNode has already been incremented under
4414 ** the cover of the unixEnterMutex() mutex and the pointer from the
4415 ** new (struct unixShm) object to the pShmNode has been set. All that is
4416 ** left to do is to link the new object into the linked list starting
4417 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4418 ** mutex.
4419 */
4420 sqlite3_mutex_enter(pShmNode->mutex);
4421 p->pNext = pShmNode->pFirst;
4422 pShmNode->pFirst = p;
4423 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004424 return SQLITE_OK;
4425
4426 /* Jump here on any error */
4427shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004428 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004429 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004430 unixLeaveMutex();
4431 return rc;
4432}
4433
4434/*
danda9fe0c2010-07-13 18:44:03 +00004435** This function is called to obtain a pointer to region iRegion of the
4436** shared-memory associated with the database file fd. Shared-memory regions
4437** are numbered starting from zero. Each shared-memory region is szRegion
4438** bytes in size.
4439**
4440** If an error occurs, an error code is returned and *pp is set to NULL.
4441**
4442** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4443** region has not been allocated (by any client, including one running in a
4444** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4445** bExtend is non-zero and the requested shared-memory region has not yet
4446** been allocated, it is allocated by this function.
4447**
4448** If the shared-memory region has already been allocated or is allocated by
4449** this call as described above, then it is mapped into this processes
4450** address space (if it is not already), *pp is set to point to the mapped
4451** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004452*/
danda9fe0c2010-07-13 18:44:03 +00004453static int unixShmMap(
4454 sqlite3_file *fd, /* Handle open on database file */
4455 int iRegion, /* Region to retrieve */
4456 int szRegion, /* Size of regions */
4457 int bExtend, /* True to extend file if necessary */
4458 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004459){
danda9fe0c2010-07-13 18:44:03 +00004460 unixFile *pDbFd = (unixFile*)fd;
4461 unixShm *p;
4462 unixShmNode *pShmNode;
4463 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004464 int nShmPerMap = unixShmRegionPerMap();
4465 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004466
danda9fe0c2010-07-13 18:44:03 +00004467 /* If the shared-memory file has not yet been opened, open it now. */
4468 if( pDbFd->pShm==0 ){
4469 rc = unixOpenSharedMemory(pDbFd);
4470 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004471 }
drhd9e5c4f2010-05-12 18:01:39 +00004472
danda9fe0c2010-07-13 18:44:03 +00004473 p = pDbFd->pShm;
4474 pShmNode = p->pShmNode;
4475 sqlite3_mutex_enter(pShmNode->mutex);
4476 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004477 assert( pShmNode->pInode==pDbFd->pInode );
4478 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4479 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004480
dan781e34c2014-03-20 08:59:47 +00004481 /* Minimum number of regions required to be mapped. */
4482 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4483
4484 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004485 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004486 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004487 struct stat sStat; /* Used by fstat() */
4488
4489 pShmNode->szRegion = szRegion;
4490
drh3cb93392011-03-12 18:10:44 +00004491 if( pShmNode->h>=0 ){
4492 /* The requested region is not mapped into this processes address space.
4493 ** Check to see if it has been allocated (i.e. if the wal-index file is
4494 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004495 */
drh3cb93392011-03-12 18:10:44 +00004496 if( osFstat(pShmNode->h, &sStat) ){
4497 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004498 goto shmpage_out;
4499 }
drh3cb93392011-03-12 18:10:44 +00004500
4501 if( sStat.st_size<nByte ){
4502 /* The requested memory region does not exist. If bExtend is set to
4503 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004504 */
dan47a2b4a2013-04-26 16:09:29 +00004505 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004506 goto shmpage_out;
4507 }
dan47a2b4a2013-04-26 16:09:29 +00004508
4509 /* Alternatively, if bExtend is true, extend the file. Do this by
4510 ** writing a single byte to the end of each (OS) page being
4511 ** allocated or extended. Technically, we need only write to the
4512 ** last page in order to extend the file. But writing to all new
4513 ** pages forces the OS to allocate them immediately, which reduces
4514 ** the chances of SIGBUS while accessing the mapped region later on.
4515 */
4516 else{
4517 static const int pgsz = 4096;
4518 int iPg;
4519
4520 /* Write to the last byte of each newly allocated or extended page */
4521 assert( (nByte % pgsz)==0 );
4522 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004523 int x = 0;
4524 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004525 const char *zFile = pShmNode->zFilename;
4526 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4527 goto shmpage_out;
4528 }
4529 }
drh3cb93392011-03-12 18:10:44 +00004530 }
4531 }
danda9fe0c2010-07-13 18:44:03 +00004532 }
4533
4534 /* Map the requested memory region into this processes address space. */
4535 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004536 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004537 );
4538 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004539 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004540 goto shmpage_out;
4541 }
4542 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004543 while( pShmNode->nRegion<nReqRegion ){
4544 int nMap = szRegion*nShmPerMap;
4545 int i;
drh3cb93392011-03-12 18:10:44 +00004546 void *pMem;
4547 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004548 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004549 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004550 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004551 );
4552 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004553 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004554 goto shmpage_out;
4555 }
4556 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004557 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004558 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004559 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004560 goto shmpage_out;
4561 }
4562 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004563 }
dan781e34c2014-03-20 08:59:47 +00004564
4565 for(i=0; i<nShmPerMap; i++){
4566 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4567 }
4568 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004569 }
4570 }
4571
4572shmpage_out:
4573 if( pShmNode->nRegion>iRegion ){
4574 *pp = pShmNode->apRegion[iRegion];
4575 }else{
4576 *pp = 0;
4577 }
drh66dfec8b2011-06-01 20:01:49 +00004578 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004579 sqlite3_mutex_leave(pShmNode->mutex);
4580 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004581}
4582
4583/*
drhd9e5c4f2010-05-12 18:01:39 +00004584** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004585**
4586** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4587** different here than in posix. In xShmLock(), one can go from unlocked
4588** to shared and back or from unlocked to exclusive and back. But one may
4589** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004590*/
4591static int unixShmLock(
4592 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004593 int ofst, /* First lock to acquire or release */
4594 int n, /* Number of locks to acquire or release */
4595 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004596){
drh73b64e42010-05-30 19:55:15 +00004597 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4598 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4599 unixShm *pX; /* For looping over all siblings */
4600 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4601 int rc = SQLITE_OK; /* Result code */
4602 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004603
drhd91c68f2010-05-14 14:52:25 +00004604 assert( pShmNode==pDbFd->pInode->pShmNode );
4605 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004606 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004607 assert( n>=1 );
4608 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4609 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4610 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4611 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4612 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004613 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4614 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004615
drhc99597c2010-05-31 01:41:15 +00004616 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004617 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004618 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004619 if( flags & SQLITE_SHM_UNLOCK ){
4620 u16 allMask = 0; /* Mask of locks held by siblings */
4621
4622 /* See if any siblings hold this same lock */
4623 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4624 if( pX==p ) continue;
4625 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4626 allMask |= pX->sharedMask;
4627 }
4628
4629 /* Unlock the system-level locks */
4630 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004631 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004632 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004633 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004634 }
drh73b64e42010-05-30 19:55:15 +00004635
4636 /* Undo the local locks */
4637 if( rc==SQLITE_OK ){
4638 p->exclMask &= ~mask;
4639 p->sharedMask &= ~mask;
4640 }
4641 }else if( flags & SQLITE_SHM_SHARED ){
4642 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4643
4644 /* Find out which shared locks are already held by sibling connections.
4645 ** If any sibling already holds an exclusive lock, go ahead and return
4646 ** SQLITE_BUSY.
4647 */
4648 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004649 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004650 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004651 break;
4652 }
4653 allShared |= pX->sharedMask;
4654 }
4655
4656 /* Get shared locks at the system level, if necessary */
4657 if( rc==SQLITE_OK ){
4658 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004659 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004660 }else{
drh73b64e42010-05-30 19:55:15 +00004661 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004662 }
drhd9e5c4f2010-05-12 18:01:39 +00004663 }
drh73b64e42010-05-30 19:55:15 +00004664
4665 /* Get the local shared locks */
4666 if( rc==SQLITE_OK ){
4667 p->sharedMask |= mask;
4668 }
4669 }else{
4670 /* Make sure no sibling connections hold locks that will block this
4671 ** lock. If any do, return SQLITE_BUSY right away.
4672 */
4673 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004674 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4675 rc = SQLITE_BUSY;
4676 break;
4677 }
4678 }
4679
4680 /* Get the exclusive locks at the system level. Then if successful
4681 ** also mark the local connection as being locked.
4682 */
4683 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004684 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004685 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004686 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004687 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004688 }
drhd9e5c4f2010-05-12 18:01:39 +00004689 }
4690 }
drhd91c68f2010-05-14 14:52:25 +00004691 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004692 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004693 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004694 return rc;
4695}
4696
drh286a2882010-05-20 23:51:06 +00004697/*
4698** Implement a memory barrier or memory fence on shared memory.
4699**
4700** All loads and stores begun before the barrier must complete before
4701** any load or store begun after the barrier.
4702*/
4703static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004704 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004705){
drhff828942010-06-26 21:34:06 +00004706 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004707 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4708 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004709 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004710}
4711
dan18801912010-06-14 14:07:50 +00004712/*
danda9fe0c2010-07-13 18:44:03 +00004713** Close a connection to shared-memory. Delete the underlying
4714** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004715**
4716** If there is no shared memory associated with the connection then this
4717** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004718*/
danda9fe0c2010-07-13 18:44:03 +00004719static int unixShmUnmap(
4720 sqlite3_file *fd, /* The underlying database file */
4721 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004722){
danda9fe0c2010-07-13 18:44:03 +00004723 unixShm *p; /* The connection to be closed */
4724 unixShmNode *pShmNode; /* The underlying shared-memory file */
4725 unixShm **pp; /* For looping over sibling connections */
4726 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004727
danda9fe0c2010-07-13 18:44:03 +00004728 pDbFd = (unixFile*)fd;
4729 p = pDbFd->pShm;
4730 if( p==0 ) return SQLITE_OK;
4731 pShmNode = p->pShmNode;
4732
4733 assert( pShmNode==pDbFd->pInode->pShmNode );
4734 assert( pShmNode->pInode==pDbFd->pInode );
4735
4736 /* Remove connection p from the set of connections associated
4737 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004738 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004739 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4740 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004741
danda9fe0c2010-07-13 18:44:03 +00004742 /* Free the connection p */
4743 sqlite3_free(p);
4744 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004745 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004746
4747 /* If pShmNode->nRef has reached 0, then close the underlying
4748 ** shared-memory file, too */
4749 unixEnterMutex();
4750 assert( pShmNode->nRef>0 );
4751 pShmNode->nRef--;
4752 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004753 if( deleteFlag && pShmNode->h>=0 ){
4754 osUnlink(pShmNode->zFilename);
4755 }
danda9fe0c2010-07-13 18:44:03 +00004756 unixShmPurge(pDbFd);
4757 }
4758 unixLeaveMutex();
4759
4760 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004761}
drh286a2882010-05-20 23:51:06 +00004762
danda9fe0c2010-07-13 18:44:03 +00004763
drhd9e5c4f2010-05-12 18:01:39 +00004764#else
drh6b017cc2010-06-14 18:01:46 +00004765# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004766# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004767# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004768# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004769#endif /* #ifndef SQLITE_OMIT_WAL */
4770
mistachkine98844f2013-08-24 00:59:24 +00004771#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004772/*
danaef49d72013-03-25 16:28:54 +00004773** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004774*/
danf23da962013-03-23 21:00:41 +00004775static void unixUnmapfile(unixFile *pFd){
4776 assert( pFd->nFetchOut==0 );
4777 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004778 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004779 pFd->pMapRegion = 0;
4780 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004781 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004782 }
4783}
dan5d8a1372013-03-19 19:28:06 +00004784
danaef49d72013-03-25 16:28:54 +00004785/*
dane6ecd662013-04-01 17:56:59 +00004786** Attempt to set the size of the memory mapping maintained by file
4787** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4788**
4789** If successful, this function sets the following variables:
4790**
4791** unixFile.pMapRegion
4792** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004793** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004794**
4795** If unsuccessful, an error message is logged via sqlite3_log() and
4796** the three variables above are zeroed. In this case SQLite should
4797** continue accessing the database using the xRead() and xWrite()
4798** methods.
4799*/
4800static void unixRemapfile(
4801 unixFile *pFd, /* File descriptor object */
4802 i64 nNew /* Required mapping size */
4803){
dan4ff7bc42013-04-02 12:04:09 +00004804 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004805 int h = pFd->h; /* File descriptor open on db file */
4806 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004807 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004808 u8 *pNew = 0; /* Location of new mapping */
4809 int flags = PROT_READ; /* Flags to pass to mmap() */
4810
4811 assert( pFd->nFetchOut==0 );
4812 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004813 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004814 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004815 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004816 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004817
danfe33e392015-11-17 20:56:06 +00004818#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004819 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004820#endif
dane6ecd662013-04-01 17:56:59 +00004821
4822 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004823#if HAVE_MREMAP
4824 i64 nReuse = pFd->mmapSize;
4825#else
danbc760632014-03-20 09:42:09 +00004826 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004827 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004828#endif
dane6ecd662013-04-01 17:56:59 +00004829 u8 *pReq = &pOrig[nReuse];
4830
4831 /* Unmap any pages of the existing mapping that cannot be reused. */
4832 if( nReuse!=nOrig ){
4833 osMunmap(pReq, nOrig-nReuse);
4834 }
4835
4836#if HAVE_MREMAP
4837 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004838 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004839#else
4840 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4841 if( pNew!=MAP_FAILED ){
4842 if( pNew!=pReq ){
4843 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004844 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004845 }else{
4846 pNew = pOrig;
4847 }
4848 }
4849#endif
4850
dan48ccef82013-04-02 20:55:01 +00004851 /* The attempt to extend the existing mapping failed. Free it. */
4852 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004853 osMunmap(pOrig, nReuse);
4854 }
4855 }
4856
4857 /* If pNew is still NULL, try to create an entirely new mapping. */
4858 if( pNew==0 ){
4859 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004860 }
4861
dan4ff7bc42013-04-02 12:04:09 +00004862 if( pNew==MAP_FAILED ){
4863 pNew = 0;
4864 nNew = 0;
4865 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4866
4867 /* If the mmap() above failed, assume that all subsequent mmap() calls
4868 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4869 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004870 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004871 }
dane6ecd662013-04-01 17:56:59 +00004872 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004873 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004874}
4875
4876/*
danaef49d72013-03-25 16:28:54 +00004877** Memory map or remap the file opened by file-descriptor pFd (if the file
4878** is already mapped, the existing mapping is replaced by the new). Or, if
4879** there already exists a mapping for this file, and there are still
4880** outstanding xFetch() references to it, this function is a no-op.
4881**
4882** If parameter nByte is non-negative, then it is the requested size of
4883** the mapping to create. Otherwise, if nByte is less than zero, then the
4884** requested size is the size of the file on disk. The actual size of the
4885** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004886** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004887**
4888** SQLITE_OK is returned if no error occurs (even if the mapping is not
4889** recreated as a result of outstanding references) or an SQLite error
4890** code otherwise.
4891*/
drhf3b1ed02015-12-02 13:11:03 +00004892static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004893 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004894 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004895 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4896
4897 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004898 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004899 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004900 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004901 }
drh3044b512014-06-16 16:41:52 +00004902 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004903 }
drh9b4c59f2013-04-15 17:03:42 +00004904 if( nMap>pFd->mmapSizeMax ){
4905 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004906 }
4907
drh333e6ca2015-12-02 15:44:39 +00004908 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004909 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004910 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004911 }
4912
danf23da962013-03-23 21:00:41 +00004913 return SQLITE_OK;
4914}
mistachkine98844f2013-08-24 00:59:24 +00004915#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004916
danaef49d72013-03-25 16:28:54 +00004917/*
4918** If possible, return a pointer to a mapping of file fd starting at offset
4919** iOff. The mapping must be valid for at least nAmt bytes.
4920**
4921** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4922** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4923** Finally, if an error does occur, return an SQLite error code. The final
4924** value of *pp is undefined in this case.
4925**
4926** If this function does return a pointer, the caller must eventually
4927** release the reference by calling unixUnfetch().
4928*/
danf23da962013-03-23 21:00:41 +00004929static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004930#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004931 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004932#endif
danf23da962013-03-23 21:00:41 +00004933 *pp = 0;
4934
drh9b4c59f2013-04-15 17:03:42 +00004935#if SQLITE_MAX_MMAP_SIZE>0
4936 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004937 if( pFd->pMapRegion==0 ){
4938 int rc = unixMapfile(pFd, -1);
4939 if( rc!=SQLITE_OK ) return rc;
4940 }
4941 if( pFd->mmapSize >= iOff+nAmt ){
4942 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4943 pFd->nFetchOut++;
4944 }
4945 }
drh6e0b6d52013-04-09 16:19:20 +00004946#endif
danf23da962013-03-23 21:00:41 +00004947 return SQLITE_OK;
4948}
4949
danaef49d72013-03-25 16:28:54 +00004950/*
dandf737fe2013-03-25 17:00:24 +00004951** If the third argument is non-NULL, then this function releases a
4952** reference obtained by an earlier call to unixFetch(). The second
4953** argument passed to this function must be the same as the corresponding
4954** argument that was passed to the unixFetch() invocation.
4955**
4956** Or, if the third argument is NULL, then this function is being called
4957** to inform the VFS layer that, according to POSIX, any existing mapping
4958** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004959*/
dandf737fe2013-03-25 17:00:24 +00004960static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004961#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004962 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004963 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004964
danaef49d72013-03-25 16:28:54 +00004965 /* If p==0 (unmap the entire file) then there must be no outstanding
4966 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4967 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004968 assert( (p==0)==(pFd->nFetchOut==0) );
4969
dandf737fe2013-03-25 17:00:24 +00004970 /* If p!=0, it must match the iOff value. */
4971 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4972
danf23da962013-03-23 21:00:41 +00004973 if( p ){
4974 pFd->nFetchOut--;
4975 }else{
4976 unixUnmapfile(pFd);
4977 }
4978
4979 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004980#else
4981 UNUSED_PARAMETER(fd);
4982 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004983 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004984#endif
danf23da962013-03-23 21:00:41 +00004985 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004986}
4987
4988/*
drh734c9862008-11-28 15:37:20 +00004989** Here ends the implementation of all sqlite3_file methods.
4990**
4991********************** End sqlite3_file Methods *******************************
4992******************************************************************************/
4993
4994/*
drh6b9d6dd2008-12-03 19:34:47 +00004995** This division contains definitions of sqlite3_io_methods objects that
4996** implement various file locking strategies. It also contains definitions
4997** of "finder" functions. A finder-function is used to locate the appropriate
4998** sqlite3_io_methods object for a particular database file. The pAppData
4999** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5000** the correct finder-function for that VFS.
5001**
5002** Most finder functions return a pointer to a fixed sqlite3_io_methods
5003** object. The only interesting finder-function is autolockIoFinder, which
5004** looks at the filesystem type and tries to guess the best locking
5005** strategy from that.
5006**
peter.d.reid60ec9142014-09-06 16:39:46 +00005007** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005008**
5009** (1) The real finder-function named "FImpt()".
5010**
dane946c392009-08-22 11:39:46 +00005011** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005012**
5013**
5014** A pointer to the F pointer is used as the pAppData value for VFS
5015** objects. We have to do this instead of letting pAppData point
5016** directly at the finder-function since C90 rules prevent a void*
5017** from be cast into a function pointer.
5018**
drh6b9d6dd2008-12-03 19:34:47 +00005019**
drh7708e972008-11-29 00:56:52 +00005020** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005021**
drh7708e972008-11-29 00:56:52 +00005022** * A constant sqlite3_io_methods object call METHOD that has locking
5023** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5024**
5025** * An I/O method finder function called FINDER that returns a pointer
5026** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005027*/
drhe6d41732015-02-21 00:49:00 +00005028#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005029static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005030 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005031 CLOSE, /* xClose */ \
5032 unixRead, /* xRead */ \
5033 unixWrite, /* xWrite */ \
5034 unixTruncate, /* xTruncate */ \
5035 unixSync, /* xSync */ \
5036 unixFileSize, /* xFileSize */ \
5037 LOCK, /* xLock */ \
5038 UNLOCK, /* xUnlock */ \
5039 CKLOCK, /* xCheckReservedLock */ \
5040 unixFileControl, /* xFileControl */ \
5041 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005042 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005043 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005044 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005045 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005046 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005047 unixFetch, /* xFetch */ \
5048 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005049}; \
drh0c2694b2009-09-03 16:23:44 +00005050static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5051 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005052 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005053} \
drh0c2694b2009-09-03 16:23:44 +00005054static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005055 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005056
5057/*
5058** Here are all of the sqlite3_io_methods objects for each of the
5059** locking strategies. Functions that return pointers to these methods
5060** are also created.
5061*/
5062IOMETHODS(
5063 posixIoFinder, /* Finder function name */
5064 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005065 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005066 unixClose, /* xClose method */
5067 unixLock, /* xLock method */
5068 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005069 unixCheckReservedLock, /* xCheckReservedLock method */
5070 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005071)
drh7708e972008-11-29 00:56:52 +00005072IOMETHODS(
5073 nolockIoFinder, /* Finder function name */
5074 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005075 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005076 nolockClose, /* xClose method */
5077 nolockLock, /* xLock method */
5078 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005079 nolockCheckReservedLock, /* xCheckReservedLock method */
5080 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005081)
drh7708e972008-11-29 00:56:52 +00005082IOMETHODS(
5083 dotlockIoFinder, /* Finder function name */
5084 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005085 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005086 dotlockClose, /* xClose method */
5087 dotlockLock, /* xLock method */
5088 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005089 dotlockCheckReservedLock, /* xCheckReservedLock method */
5090 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005091)
drh7708e972008-11-29 00:56:52 +00005092
drhe89b2912015-03-03 20:42:01 +00005093#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005094IOMETHODS(
5095 flockIoFinder, /* Finder function name */
5096 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005097 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005098 flockClose, /* xClose method */
5099 flockLock, /* xLock method */
5100 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005101 flockCheckReservedLock, /* xCheckReservedLock method */
5102 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005103)
drh7708e972008-11-29 00:56:52 +00005104#endif
5105
drh6c7d5c52008-11-21 20:32:33 +00005106#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005107IOMETHODS(
5108 semIoFinder, /* Finder function name */
5109 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005110 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005111 semXClose, /* xClose method */
5112 semXLock, /* xLock method */
5113 semXUnlock, /* xUnlock method */
5114 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005115 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005116)
aswiftaebf4132008-11-21 00:10:35 +00005117#endif
drh7708e972008-11-29 00:56:52 +00005118
drhd2cb50b2009-01-09 21:41:17 +00005119#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005120IOMETHODS(
5121 afpIoFinder, /* Finder function name */
5122 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005123 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005124 afpClose, /* xClose method */
5125 afpLock, /* xLock method */
5126 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005127 afpCheckReservedLock, /* xCheckReservedLock method */
5128 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005129)
drh715ff302008-12-03 22:32:44 +00005130#endif
5131
5132/*
5133** The proxy locking method is a "super-method" in the sense that it
5134** opens secondary file descriptors for the conch and lock files and
5135** it uses proxy, dot-file, AFP, and flock() locking methods on those
5136** secondary files. For this reason, the division that implements
5137** proxy locking is located much further down in the file. But we need
5138** to go ahead and define the sqlite3_io_methods and finder function
5139** for proxy locking here. So we forward declare the I/O methods.
5140*/
drhd2cb50b2009-01-09 21:41:17 +00005141#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005142static int proxyClose(sqlite3_file*);
5143static int proxyLock(sqlite3_file*, int);
5144static int proxyUnlock(sqlite3_file*, int);
5145static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005146IOMETHODS(
5147 proxyIoFinder, /* Finder function name */
5148 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005149 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005150 proxyClose, /* xClose method */
5151 proxyLock, /* xLock method */
5152 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005153 proxyCheckReservedLock, /* xCheckReservedLock method */
5154 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005155)
aswiftaebf4132008-11-21 00:10:35 +00005156#endif
drh7708e972008-11-29 00:56:52 +00005157
drh7ed97b92010-01-20 13:07:21 +00005158/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5159#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5160IOMETHODS(
5161 nfsIoFinder, /* Finder function name */
5162 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005163 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005164 unixClose, /* xClose method */
5165 unixLock, /* xLock method */
5166 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005167 unixCheckReservedLock, /* xCheckReservedLock method */
5168 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005169)
5170#endif
drh7708e972008-11-29 00:56:52 +00005171
drhd2cb50b2009-01-09 21:41:17 +00005172#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005173/*
drh6b9d6dd2008-12-03 19:34:47 +00005174** This "finder" function attempts to determine the best locking strategy
5175** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005176** object that implements that strategy.
5177**
5178** This is for MacOSX only.
5179*/
drh1875f7a2008-12-08 18:19:17 +00005180static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005181 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005182 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005183){
5184 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005185 const char *zFilesystem; /* Filesystem type name */
5186 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005187 } aMap[] = {
5188 { "hfs", &posixIoMethods },
5189 { "ufs", &posixIoMethods },
5190 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005191 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005192 { "webdav", &nolockIoMethods },
5193 { 0, 0 }
5194 };
5195 int i;
5196 struct statfs fsInfo;
5197 struct flock lockInfo;
5198
5199 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005200 /* If filePath==NULL that means we are dealing with a transient file
5201 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005202 return &nolockIoMethods;
5203 }
5204 if( statfs(filePath, &fsInfo) != -1 ){
5205 if( fsInfo.f_flags & MNT_RDONLY ){
5206 return &nolockIoMethods;
5207 }
5208 for(i=0; aMap[i].zFilesystem; i++){
5209 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5210 return aMap[i].pMethods;
5211 }
5212 }
5213 }
5214
5215 /* Default case. Handles, amongst others, "nfs".
5216 ** Test byte-range lock using fcntl(). If the call succeeds,
5217 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005218 */
drh7708e972008-11-29 00:56:52 +00005219 lockInfo.l_len = 1;
5220 lockInfo.l_start = 0;
5221 lockInfo.l_whence = SEEK_SET;
5222 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005223 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005224 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5225 return &nfsIoMethods;
5226 } else {
5227 return &posixIoMethods;
5228 }
drh7708e972008-11-29 00:56:52 +00005229 }else{
5230 return &dotlockIoMethods;
5231 }
5232}
drh0c2694b2009-09-03 16:23:44 +00005233static const sqlite3_io_methods
5234 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005235
drhd2cb50b2009-01-09 21:41:17 +00005236#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005237
drhe89b2912015-03-03 20:42:01 +00005238#if OS_VXWORKS
5239/*
5240** This "finder" function for VxWorks checks to see if posix advisory
5241** locking works. If it does, then that is what is used. If it does not
5242** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005243*/
drhe89b2912015-03-03 20:42:01 +00005244static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005245 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005246 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005247){
5248 struct flock lockInfo;
5249
5250 if( !filePath ){
5251 /* If filePath==NULL that means we are dealing with a transient file
5252 ** that does not need to be locked. */
5253 return &nolockIoMethods;
5254 }
5255
5256 /* Test if fcntl() is supported and use POSIX style locks.
5257 ** Otherwise fall back to the named semaphore method.
5258 */
5259 lockInfo.l_len = 1;
5260 lockInfo.l_start = 0;
5261 lockInfo.l_whence = SEEK_SET;
5262 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005263 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005264 return &posixIoMethods;
5265 }else{
5266 return &semIoMethods;
5267 }
5268}
drh0c2694b2009-09-03 16:23:44 +00005269static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005270 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005271
drhe89b2912015-03-03 20:42:01 +00005272#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005273
drh7708e972008-11-29 00:56:52 +00005274/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005275** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005276*/
drh0c2694b2009-09-03 16:23:44 +00005277typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005278
aswiftaebf4132008-11-21 00:10:35 +00005279
drh734c9862008-11-28 15:37:20 +00005280/****************************************************************************
5281**************************** sqlite3_vfs methods ****************************
5282**
5283** This division contains the implementation of methods on the
5284** sqlite3_vfs object.
5285*/
5286
danielk1977a3d4c882007-03-23 10:08:38 +00005287/*
danielk1977e339d652008-06-28 11:23:00 +00005288** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005289*/
5290static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005291 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005292 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005293 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005294 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005295 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005296){
drh7708e972008-11-29 00:56:52 +00005297 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005298 unixFile *pNew = (unixFile *)pId;
5299 int rc = SQLITE_OK;
5300
drh8af6c222010-05-14 12:43:01 +00005301 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005302
drhb07028f2011-10-14 21:49:18 +00005303 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005304 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005305
drh308c2a52010-05-14 11:30:18 +00005306 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005307 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005308 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005309 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005310 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005311#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005312 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005313#endif
drhc02a43a2012-01-10 23:18:38 +00005314 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5315 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005316 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005317 }
drh503a6862013-03-01 01:07:17 +00005318 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005319 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005320 }
drh339eb0b2008-03-07 15:34:11 +00005321
drh6c7d5c52008-11-21 20:32:33 +00005322#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005323 pNew->pId = vxworksFindFileId(zFilename);
5324 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005325 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005326 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005327 }
5328#endif
5329
drhc02a43a2012-01-10 23:18:38 +00005330 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005331 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005332 }else{
drh0c2694b2009-09-03 16:23:44 +00005333 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005334#if SQLITE_ENABLE_LOCKING_STYLE
5335 /* Cache zFilename in the locking context (AFP and dotlock override) for
5336 ** proxyLock activation is possible (remote proxy is based on db name)
5337 ** zFilename remains valid until file is closed, to support */
5338 pNew->lockingContext = (void*)zFilename;
5339#endif
drhda0e7682008-07-30 15:27:54 +00005340 }
danielk1977e339d652008-06-28 11:23:00 +00005341
drh7ed97b92010-01-20 13:07:21 +00005342 if( pLockingStyle == &posixIoMethods
5343#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5344 || pLockingStyle == &nfsIoMethods
5345#endif
5346 ){
drh7708e972008-11-29 00:56:52 +00005347 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005348 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005349 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005350 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005351 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005352 ** in two scenarios:
5353 **
5354 ** (a) A call to fstat() failed.
5355 ** (b) A malloc failed.
5356 **
5357 ** Scenario (b) may only occur if the process is holding no other
5358 ** file descriptors open on the same file. If there were other file
5359 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005360 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005361 ** handle h - as it is guaranteed that no posix locks will be released
5362 ** by doing so.
5363 **
5364 ** If scenario (a) caused the error then things are not so safe. The
5365 ** implicit assumption here is that if fstat() fails, things are in
5366 ** such bad shape that dropping a lock or two doesn't matter much.
5367 */
drh0e9365c2011-03-02 02:08:13 +00005368 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005369 h = -1;
5370 }
drh7708e972008-11-29 00:56:52 +00005371 unixLeaveMutex();
5372 }
danielk1977e339d652008-06-28 11:23:00 +00005373
drhd2cb50b2009-01-09 21:41:17 +00005374#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005375 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005376 /* AFP locking uses the file path so it needs to be included in
5377 ** the afpLockingContext.
5378 */
5379 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005380 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005381 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005382 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005383 }else{
5384 /* NB: zFilename exists and remains valid until the file is closed
5385 ** according to requirement F11141. So we do not need to make a
5386 ** copy of the filename. */
5387 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005388 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005389 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005390 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005391 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005392 if( rc!=SQLITE_OK ){
5393 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005394 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005395 h = -1;
5396 }
drh7708e972008-11-29 00:56:52 +00005397 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005398 }
drh7708e972008-11-29 00:56:52 +00005399 }
5400#endif
danielk1977e339d652008-06-28 11:23:00 +00005401
drh7708e972008-11-29 00:56:52 +00005402 else if( pLockingStyle == &dotlockIoMethods ){
5403 /* Dotfile locking uses the file path so it needs to be included in
5404 ** the dotlockLockingContext
5405 */
5406 char *zLockFile;
5407 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005408 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005409 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005410 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005411 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005412 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005413 }else{
5414 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005415 }
drh7708e972008-11-29 00:56:52 +00005416 pNew->lockingContext = zLockFile;
5417 }
danielk1977e339d652008-06-28 11:23:00 +00005418
drh6c7d5c52008-11-21 20:32:33 +00005419#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005420 else if( pLockingStyle == &semIoMethods ){
5421 /* Named semaphore locking uses the file path so it needs to be
5422 ** included in the semLockingContext
5423 */
5424 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005425 rc = findInodeInfo(pNew, &pNew->pInode);
5426 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5427 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005428 int n;
drh2238dcc2009-08-27 17:56:20 +00005429 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005430 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005431 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005432 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005433 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5434 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005435 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005436 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005437 }
chw97185482008-11-17 08:05:31 +00005438 }
drh7708e972008-11-29 00:56:52 +00005439 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005440 }
drh7708e972008-11-29 00:56:52 +00005441#endif
aswift5b1a2562008-08-22 00:22:35 +00005442
drh4bf66fd2015-02-19 02:43:02 +00005443 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005444#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005445 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005446 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005447 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005448 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005449 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005450 }
chw97185482008-11-17 08:05:31 +00005451#endif
danielk1977e339d652008-06-28 11:23:00 +00005452 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005453 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005454 }else{
drh7708e972008-11-29 00:56:52 +00005455 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005456 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005457 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005458 }
danielk1977e339d652008-06-28 11:23:00 +00005459 return rc;
drh054889e2005-11-30 03:20:31 +00005460}
drh9c06c952005-11-26 00:25:00 +00005461
danielk1977ad94b582007-08-20 06:44:22 +00005462/*
drh8b3cf822010-06-01 21:02:51 +00005463** Return the name of a directory in which to put temporary files.
5464** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005465*/
drh7234c6d2010-06-19 15:10:09 +00005466static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005467 static const char *azDirs[] = {
5468 0,
aswiftaebf4132008-11-21 00:10:35 +00005469 0,
danielk197717b90b52008-06-06 11:11:25 +00005470 "/var/tmp",
5471 "/usr/tmp",
5472 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005473 "."
danielk197717b90b52008-06-06 11:11:25 +00005474 };
drh2aab11f2016-04-29 20:30:56 +00005475 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005476 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005477 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005478
drhb7e50ad2015-11-28 21:49:53 +00005479 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5480 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005481 while(1){
5482 if( zDir!=0
5483 && osStat(zDir, &buf)==0
5484 && S_ISDIR(buf.st_mode)
5485 && osAccess(zDir, 03)==0
5486 ){
5487 return zDir;
5488 }
5489 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5490 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005491 }
drh7694e062016-04-21 23:37:24 +00005492 return 0;
drh8b3cf822010-06-01 21:02:51 +00005493}
5494
5495/*
5496** Create a temporary file name in zBuf. zBuf must be allocated
5497** by the calling process and must be big enough to hold at least
5498** pVfs->mxPathname bytes.
5499*/
5500static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005501 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005502 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005503
5504 /* It's odd to simulate an io-error here, but really this is just
5505 ** using the io-error infrastructure to test that SQLite handles this
5506 ** function failing.
5507 */
drh7694e062016-04-21 23:37:24 +00005508 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005509 SimulateIOError( return SQLITE_IOERR );
5510
drh7234c6d2010-06-19 15:10:09 +00005511 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005512 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005513 do{
drh970942e2015-11-25 23:13:14 +00005514 u64 r;
5515 sqlite3_randomness(sizeof(r), &r);
5516 assert( nBuf>2 );
5517 zBuf[nBuf-2] = 0;
5518 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5519 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005520 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005521 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005522 return SQLITE_OK;
5523}
5524
drhd2cb50b2009-01-09 21:41:17 +00005525#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005526/*
5527** Routine to transform a unixFile into a proxy-locking unixFile.
5528** Implementation in the proxy-lock division, but used by unixOpen()
5529** if SQLITE_PREFER_PROXY_LOCKING is defined.
5530*/
5531static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005532#endif
drhc66d5b62008-12-03 22:48:32 +00005533
dan08da86a2009-08-21 17:18:03 +00005534/*
5535** Search for an unused file descriptor that was opened on the database
5536** file (not a journal or master-journal file) identified by pathname
5537** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5538** argument to this function.
5539**
5540** Such a file descriptor may exist if a database connection was closed
5541** but the associated file descriptor could not be closed because some
5542** other file descriptor open on the same file is holding a file-lock.
5543** Refer to comments in the unixClose() function and the lengthy comment
5544** describing "Posix Advisory Locking" at the start of this file for
5545** further details. Also, ticket #4018.
5546**
5547** If a suitable file descriptor is found, then it is returned. If no
5548** such file descriptor is located, -1 is returned.
5549*/
dane946c392009-08-22 11:39:46 +00005550static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5551 UnixUnusedFd *pUnused = 0;
5552
5553 /* Do not search for an unused file descriptor on vxworks. Not because
5554 ** vxworks would not benefit from the change (it might, we're not sure),
5555 ** but because no way to test it is currently available. It is better
5556 ** not to risk breaking vxworks support for the sake of such an obscure
5557 ** feature. */
5558#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005559 struct stat sStat; /* Results of stat() call */
5560
drhc68886b2017-08-18 16:09:52 +00005561 unixEnterMutex();
5562
dan08da86a2009-08-21 17:18:03 +00005563 /* A stat() call may fail for various reasons. If this happens, it is
5564 ** almost certain that an open() call on the same path will also fail.
5565 ** For this reason, if an error occurs in the stat() call here, it is
5566 ** ignored and -1 is returned. The caller will try to open a new file
5567 ** descriptor on the same path, fail, and return an error to SQLite.
5568 **
5569 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005570 ** not searching for a reusable file descriptor are not dire. */
drhc68886b2017-08-18 16:09:52 +00005571 if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005572 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005573
drh8af6c222010-05-14 12:43:01 +00005574 pInode = inodeList;
5575 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005576 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005577 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005578 }
drh8af6c222010-05-14 12:43:01 +00005579 if( pInode ){
dane946c392009-08-22 11:39:46 +00005580 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005581 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005582 pUnused = *pp;
5583 if( pUnused ){
drhc68886b2017-08-18 16:09:52 +00005584 nUnusedFd--;
dane946c392009-08-22 11:39:46 +00005585 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005586 }
5587 }
dan08da86a2009-08-21 17:18:03 +00005588 }
drhc68886b2017-08-18 16:09:52 +00005589 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005590#endif /* if !OS_VXWORKS */
5591 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005592}
danielk197717b90b52008-06-06 11:11:25 +00005593
5594/*
dan1bf4ca72016-08-11 18:05:47 +00005595** Find the mode, uid and gid of file zFile.
5596*/
5597static int getFileMode(
5598 const char *zFile, /* File name */
5599 mode_t *pMode, /* OUT: Permissions of zFile */
5600 uid_t *pUid, /* OUT: uid of zFile. */
5601 gid_t *pGid /* OUT: gid of zFile. */
5602){
5603 struct stat sStat; /* Output of stat() on database file */
5604 int rc = SQLITE_OK;
5605 if( 0==osStat(zFile, &sStat) ){
5606 *pMode = sStat.st_mode & 0777;
5607 *pUid = sStat.st_uid;
5608 *pGid = sStat.st_gid;
5609 }else{
5610 rc = SQLITE_IOERR_FSTAT;
5611 }
5612 return rc;
5613}
5614
5615/*
danddb0ac42010-07-14 14:48:58 +00005616** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005617** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005618** and a value suitable for passing as the third argument to open(2) is
5619** written to *pMode. If an IO error occurs, an SQLite error code is
5620** returned and the value of *pMode is not modified.
5621**
peter.d.reid60ec9142014-09-06 16:39:46 +00005622** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005623** an indication to robust_open() to create the file using
5624** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5625** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005626** this function queries the file-system for the permissions on the
5627** corresponding database file and sets *pMode to this value. Whenever
5628** possible, WAL and journal files are created using the same permissions
5629** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005630**
5631** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5632** original filename is unavailable. But 8_3_NAMES is only used for
5633** FAT filesystems and permissions do not matter there, so just use
5634** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005635*/
5636static int findCreateFileMode(
5637 const char *zPath, /* Path of file (possibly) being created */
5638 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005639 mode_t *pMode, /* OUT: Permissions to open file with */
5640 uid_t *pUid, /* OUT: uid to set on the file */
5641 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005642){
5643 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005644 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005645 *pUid = 0;
5646 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005647 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005648 char zDb[MAX_PATHNAME+1]; /* Database file path */
5649 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005650
dana0c989d2010-11-05 18:07:37 +00005651 /* zPath is a path to a WAL or journal file. The following block derives
5652 ** the path to the associated database file from zPath. This block handles
5653 ** the following naming conventions:
5654 **
5655 ** "<path to db>-journal"
5656 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005657 ** "<path to db>-journalNN"
5658 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005659 **
drhd337c5b2011-10-20 18:23:35 +00005660 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005661 ** used by the test_multiplex.c module.
5662 */
5663 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005664 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005665 /* In normal operation, the journal file name will always contain
5666 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5667 ** rollback journal specifies a master journal with a goofy name, then
5668 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005669 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005670 nDb--;
5671 }
danddb0ac42010-07-14 14:48:58 +00005672 memcpy(zDb, zPath, nDb);
5673 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005674
dan1bf4ca72016-08-11 18:05:47 +00005675 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005676 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5677 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005678 }else if( flags & SQLITE_OPEN_URI ){
5679 /* If this is a main database file and the file was opened using a URI
5680 ** filename, check for the "modeof" parameter. If present, interpret
5681 ** its value as a filename and try to copy the mode, uid and gid from
5682 ** that file. */
5683 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5684 if( z ){
5685 rc = getFileMode(z, pMode, pUid, pGid);
5686 }
danddb0ac42010-07-14 14:48:58 +00005687 }
5688 return rc;
5689}
5690
5691/*
danielk1977ad94b582007-08-20 06:44:22 +00005692** Open the file zPath.
5693**
danielk1977b4b47412007-08-17 15:53:36 +00005694** Previously, the SQLite OS layer used three functions in place of this
5695** one:
5696**
5697** sqlite3OsOpenReadWrite();
5698** sqlite3OsOpenReadOnly();
5699** sqlite3OsOpenExclusive();
5700**
5701** These calls correspond to the following combinations of flags:
5702**
5703** ReadWrite() -> (READWRITE | CREATE)
5704** ReadOnly() -> (READONLY)
5705** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5706**
5707** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5708** true, the file was configured to be automatically deleted when the
5709** file handle closed. To achieve the same effect using this new
5710** interface, add the DELETEONCLOSE flag to those specified above for
5711** OpenExclusive().
5712*/
5713static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005714 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5715 const char *zPath, /* Pathname of file to be opened */
5716 sqlite3_file *pFile, /* The file descriptor to be filled in */
5717 int flags, /* Input flags to control the opening */
5718 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005719){
dan08da86a2009-08-21 17:18:03 +00005720 unixFile *p = (unixFile *)pFile;
5721 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005722 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005723 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005724 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005725 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005726 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005727
5728 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5729 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5730 int isCreate = (flags & SQLITE_OPEN_CREATE);
5731 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5732 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005733#if SQLITE_ENABLE_LOCKING_STYLE
5734 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5735#endif
drh3d4435b2011-08-26 20:55:50 +00005736#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5737 struct statfs fsInfo;
5738#endif
danielk1977b4b47412007-08-17 15:53:36 +00005739
danielk1977fee2d252007-08-18 10:59:19 +00005740 /* If creating a master or main-file journal, this function will open
5741 ** a file-descriptor on the directory too. The first time unixSync()
5742 ** is called the directory file descriptor will be fsync()ed and close()d.
5743 */
drh0059eae2011-08-08 23:48:40 +00005744 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005745 eType==SQLITE_OPEN_MASTER_JOURNAL
5746 || eType==SQLITE_OPEN_MAIN_JOURNAL
5747 || eType==SQLITE_OPEN_WAL
5748 ));
danielk1977fee2d252007-08-18 10:59:19 +00005749
danielk197717b90b52008-06-06 11:11:25 +00005750 /* If argument zPath is a NULL pointer, this function is required to open
5751 ** a temporary file. Use this buffer to store the file name in.
5752 */
drhc02a43a2012-01-10 23:18:38 +00005753 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005754 const char *zName = zPath;
5755
danielk1977fee2d252007-08-18 10:59:19 +00005756 /* Check the following statements are true:
5757 **
5758 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5759 ** (b) if CREATE is set, then READWRITE must also be set, and
5760 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005761 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005762 */
danielk1977b4b47412007-08-17 15:53:36 +00005763 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005764 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005765 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005766 assert(isDelete==0 || isCreate);
5767
danddb0ac42010-07-14 14:48:58 +00005768 /* The main DB, main journal, WAL file and master journal are never
5769 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005770 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5771 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5772 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005773 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005774
danielk1977fee2d252007-08-18 10:59:19 +00005775 /* Assert that the upper layer has set one of the "file-type" flags. */
5776 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5777 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5778 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005779 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005780 );
5781
drhb00d8622014-01-01 15:18:36 +00005782 /* Detect a pid change and reset the PRNG. There is a race condition
5783 ** here such that two or more threads all trying to open databases at
5784 ** the same instant might all reset the PRNG. But multiple resets
5785 ** are harmless.
5786 */
drh5ac93652015-03-21 20:59:43 +00005787 if( randomnessPid!=osGetpid(0) ){
5788 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005789 sqlite3_randomness(0,0);
5790 }
5791
dan08da86a2009-08-21 17:18:03 +00005792 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005793
dan08da86a2009-08-21 17:18:03 +00005794 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005795 UnixUnusedFd *pUnused;
5796 pUnused = findReusableFd(zName, flags);
5797 if( pUnused ){
5798 fd = pUnused->fd;
5799 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005800 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005801 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005802 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005803 }
5804 }
drhc68886b2017-08-18 16:09:52 +00005805 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005806
5807 /* Database filenames are double-zero terminated if they are not
5808 ** URIs with parameters. Hence, they can always be passed into
5809 ** sqlite3_uri_parameter(). */
5810 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5811
dan08da86a2009-08-21 17:18:03 +00005812 }else if( !zName ){
5813 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005814 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005815 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005816 if( rc!=SQLITE_OK ){
5817 return rc;
5818 }
5819 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005820
5821 /* Generated temporary filenames are always double-zero terminated
5822 ** for use by sqlite3_uri_parameter(). */
5823 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005824 }
5825
dan08da86a2009-08-21 17:18:03 +00005826 /* Determine the value of the flags parameter passed to POSIX function
5827 ** open(). These must be calculated even if open() is not called, as
5828 ** they may be stored as part of the file handle and used by the
5829 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005830 if( isReadonly ) openFlags |= O_RDONLY;
5831 if( isReadWrite ) openFlags |= O_RDWR;
5832 if( isCreate ) openFlags |= O_CREAT;
5833 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5834 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005835
danielk1977b4b47412007-08-17 15:53:36 +00005836 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005837 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005838 uid_t uid; /* Userid for the file */
5839 gid_t gid; /* Groupid for the file */
5840 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005841 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00005842 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00005843 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005844 return rc;
5845 }
drhad4f1e52011-03-04 15:43:57 +00005846 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005847 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005848 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5849 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005850 /* Failed to open the file for read/write access. Try read-only. */
5851 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005852 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005853 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005854 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005855 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005856 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005857 }
5858 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005859 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005860 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005861 }
drhac7c3ac2012-02-11 19:23:48 +00005862
5863 /* If this process is running as root and if creating a new rollback
5864 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005865 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005866 */
5867 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005868 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005869 }
danielk1977b4b47412007-08-17 15:53:36 +00005870 }
dan08da86a2009-08-21 17:18:03 +00005871 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005872 if( pOutFlags ){
5873 *pOutFlags = flags;
5874 }
5875
drhc68886b2017-08-18 16:09:52 +00005876 if( p->pPreallocatedUnused ){
5877 p->pPreallocatedUnused->fd = fd;
5878 p->pPreallocatedUnused->flags = flags;
dane946c392009-08-22 11:39:46 +00005879 }
5880
danielk1977b4b47412007-08-17 15:53:36 +00005881 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005882#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005883 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005884#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5885 zPath = sqlite3_mprintf("%s", zName);
5886 if( zPath==0 ){
5887 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00005888 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00005889 }
chw97185482008-11-17 08:05:31 +00005890#else
drh036ac7f2011-08-08 23:18:05 +00005891 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005892#endif
danielk1977b4b47412007-08-17 15:53:36 +00005893 }
drh41022642008-11-21 00:24:42 +00005894#if SQLITE_ENABLE_LOCKING_STYLE
5895 else{
dan08da86a2009-08-21 17:18:03 +00005896 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005897 }
5898#endif
drh7ed97b92010-01-20 13:07:21 +00005899
5900#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005901 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005902 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005903 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005904 return SQLITE_IOERR_ACCESS;
5905 }
5906 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5907 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5908 }
drh4bf66fd2015-02-19 02:43:02 +00005909 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5910 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5911 }
drh7ed97b92010-01-20 13:07:21 +00005912#endif
drhc02a43a2012-01-10 23:18:38 +00005913
5914 /* Set up appropriate ctrlFlags */
5915 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5916 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00005917 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00005918 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5919 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5920 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5921
drh7ed97b92010-01-20 13:07:21 +00005922#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005923#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005924 isAutoProxy = 1;
5925#endif
5926 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005927 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5928 int useProxy = 0;
5929
dan08da86a2009-08-21 17:18:03 +00005930 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5931 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005932 if( envforce!=NULL ){
5933 useProxy = atoi(envforce)>0;
5934 }else{
aswiftaebf4132008-11-21 00:10:35 +00005935 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5936 }
5937 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005938 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005939 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005940 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005941 if( rc!=SQLITE_OK ){
5942 /* Use unixClose to clean up the resources added in fillInUnixFile
5943 ** and clear all the structure's references. Specifically,
5944 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5945 */
5946 unixClose(pFile);
5947 return rc;
5948 }
aswiftaebf4132008-11-21 00:10:35 +00005949 }
dane946c392009-08-22 11:39:46 +00005950 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005951 }
5952 }
5953#endif
5954
dan629ec142017-09-14 20:41:17 +00005955 assert( zPath==0 || zPath[0]=='/' || eType==SQLITE_OPEN_MASTER_JOURNAL );
drhc02a43a2012-01-10 23:18:38 +00005956 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5957
dane946c392009-08-22 11:39:46 +00005958open_finished:
5959 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00005960 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00005961 }
5962 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005963}
5964
dane946c392009-08-22 11:39:46 +00005965
danielk1977b4b47412007-08-17 15:53:36 +00005966/*
danielk1977fee2d252007-08-18 10:59:19 +00005967** Delete the file at zPath. If the dirSync argument is true, fsync()
5968** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005969*/
drh6b9d6dd2008-12-03 19:34:47 +00005970static int unixDelete(
5971 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5972 const char *zPath, /* Name of file to be deleted */
5973 int dirSync /* If true, fsync() directory after deleting file */
5974){
danielk1977fee2d252007-08-18 10:59:19 +00005975 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005976 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005977 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005978 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005979 if( errno==ENOENT
5980#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005981 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005982#endif
5983 ){
dan9fc5b4a2012-11-09 20:17:26 +00005984 rc = SQLITE_IOERR_DELETE_NOENT;
5985 }else{
drhb4308162012-11-09 21:40:02 +00005986 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005987 }
drhb4308162012-11-09 21:40:02 +00005988 return rc;
drh5d4feff2010-07-14 01:45:22 +00005989 }
danielk1977d39fa702008-10-16 13:27:40 +00005990#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005991 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005992 int fd;
drh90315a22011-08-10 01:52:12 +00005993 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005994 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00005995 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00005996 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005997 }
drh0e9365c2011-03-02 02:08:13 +00005998 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005999 }else{
6000 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006001 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006002 }
6003 }
danielk1977d138dd82008-10-15 16:02:48 +00006004#endif
danielk1977fee2d252007-08-18 10:59:19 +00006005 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006006}
6007
danielk197790949c22007-08-17 16:50:38 +00006008/*
mistachkin48864df2013-03-21 21:20:32 +00006009** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006010** test performed depends on the value of flags:
6011**
6012** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6013** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6014** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6015**
6016** Otherwise return 0.
6017*/
danielk1977861f7452008-06-05 11:39:11 +00006018static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006019 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6020 const char *zPath, /* Path of the file to examine */
6021 int flags, /* What do we want to learn about the zPath file? */
6022 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006023){
danielk1977397d65f2008-11-19 11:35:39 +00006024 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006025 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006026 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006027
drhd260b5b2015-11-25 18:03:33 +00006028 /* The spec says there are three possible values for flags. But only
6029 ** two of them are actually used */
6030 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6031
6032 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006033 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006034 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6035 }else{
6036 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006037 }
danielk1977861f7452008-06-05 11:39:11 +00006038 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006039}
6040
danielk1977b4b47412007-08-17 15:53:36 +00006041/*
danielk1977b4b47412007-08-17 15:53:36 +00006042**
danielk1977b4b47412007-08-17 15:53:36 +00006043*/
dane88ec182016-01-25 17:04:48 +00006044static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006045 const char *zPath, /* Input path */
6046 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006047 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006048){
dancaf6b152016-01-25 18:05:49 +00006049 int nPath = sqlite3Strlen30(zPath);
6050 int iOff = 0;
6051 if( zPath[0]!='/' ){
6052 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006053 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006054 }
dancaf6b152016-01-25 18:05:49 +00006055 iOff = sqlite3Strlen30(zOut);
6056 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006057 }
dan23496702016-01-26 13:56:42 +00006058 if( (iOff+nPath+1)>nOut ){
6059 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6060 ** even if it returns an error. */
6061 zOut[iOff] = '\0';
6062 return SQLITE_CANTOPEN_BKPT;
6063 }
dancaf6b152016-01-25 18:05:49 +00006064 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006065 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006066}
6067
dane88ec182016-01-25 17:04:48 +00006068/*
6069** Turn a relative pathname into a full pathname. The relative path
6070** is stored as a nul-terminated string in the buffer pointed to by
6071** zPath.
6072**
6073** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6074** (in this case, MAX_PATHNAME bytes). The full-path is written to
6075** this buffer before returning.
6076*/
6077static int unixFullPathname(
6078 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6079 const char *zPath, /* Possibly relative input path */
6080 int nOut, /* Size of output buffer in bytes */
6081 char *zOut /* Output buffer */
6082){
danaf1b36b2016-01-25 18:43:05 +00006083#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006084 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006085#else
6086 int rc = SQLITE_OK;
6087 int nByte;
dancaf6b152016-01-25 18:05:49 +00006088 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006089 const char *zIn = zPath; /* Input path for each iteration of loop */
6090 char *zDel = 0;
6091
6092 assert( pVfs->mxPathname==MAX_PATHNAME );
6093 UNUSED_PARAMETER(pVfs);
6094
6095 /* It's odd to simulate an io-error here, but really this is just
6096 ** using the io-error infrastructure to test that SQLite handles this
6097 ** function failing. This function could fail if, for example, the
6098 ** current working directory has been unlinked.
6099 */
6100 SimulateIOError( return SQLITE_ERROR );
6101
6102 do {
6103
dancaf6b152016-01-25 18:05:49 +00006104 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6105 ** link, or false otherwise. */
6106 int bLink = 0;
6107 struct stat buf;
6108 if( osLstat(zIn, &buf)!=0 ){
6109 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006110 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006111 }
dane88ec182016-01-25 17:04:48 +00006112 }else{
dancaf6b152016-01-25 18:05:49 +00006113 bLink = S_ISLNK(buf.st_mode);
6114 }
6115
6116 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006117 if( zDel==0 ){
6118 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006119 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006120 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6121 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006122 }
dancaf6b152016-01-25 18:05:49 +00006123
6124 if( rc==SQLITE_OK ){
6125 nByte = osReadlink(zIn, zDel, nOut-1);
6126 if( nByte<0 ){
6127 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006128 }else{
6129 if( zDel[0]!='/' ){
6130 int n;
6131 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6132 if( nByte+n+1>nOut ){
6133 rc = SQLITE_CANTOPEN_BKPT;
6134 }else{
6135 memmove(&zDel[n], zDel, nByte+1);
6136 memcpy(zDel, zIn, n);
6137 nByte += n;
6138 }
dancaf6b152016-01-25 18:05:49 +00006139 }
6140 zDel[nByte] = '\0';
6141 }
6142 }
6143
6144 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006145 }
6146
dan23496702016-01-26 13:56:42 +00006147 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6148 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006149 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006150 }
dancaf6b152016-01-25 18:05:49 +00006151 if( bLink==0 ) break;
6152 zIn = zOut;
6153 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006154
6155 sqlite3_free(zDel);
6156 return rc;
danaf1b36b2016-01-25 18:43:05 +00006157#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006158}
6159
drh0ccebe72005-06-07 22:22:50 +00006160
drh761df872006-12-21 01:29:22 +00006161#ifndef SQLITE_OMIT_LOAD_EXTENSION
6162/*
6163** Interfaces for opening a shared library, finding entry points
6164** within the shared library, and closing the shared library.
6165*/
6166#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006167static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6168 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006169 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6170}
danielk197795c8a542007-09-01 06:51:27 +00006171
6172/*
6173** SQLite calls this function immediately after a call to unixDlSym() or
6174** unixDlOpen() fails (returns a null pointer). If a more detailed error
6175** message is available, it is written to zBufOut. If no error message
6176** is available, zBufOut is left unmodified and SQLite uses a default
6177** error message.
6178*/
danielk1977397d65f2008-11-19 11:35:39 +00006179static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006180 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006181 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006182 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006183 zErr = dlerror();
6184 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006185 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006186 }
drh6c7d5c52008-11-21 20:32:33 +00006187 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006188}
drh1875f7a2008-12-08 18:19:17 +00006189static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6190 /*
6191 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6192 ** cast into a pointer to a function. And yet the library dlsym() routine
6193 ** returns a void* which is really a pointer to a function. So how do we
6194 ** use dlsym() with -pedantic-errors?
6195 **
6196 ** Variable x below is defined to be a pointer to a function taking
6197 ** parameters void* and const char* and returning a pointer to a function.
6198 ** We initialize x by assigning it a pointer to the dlsym() function.
6199 ** (That assignment requires a cast.) Then we call the function that
6200 ** x points to.
6201 **
6202 ** This work-around is unlikely to work correctly on any system where
6203 ** you really cannot cast a function pointer into void*. But then, on the
6204 ** other hand, dlsym() will not work on such a system either, so we have
6205 ** not really lost anything.
6206 */
6207 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006208 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006209 x = (void(*(*)(void*,const char*))(void))dlsym;
6210 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006211}
danielk1977397d65f2008-11-19 11:35:39 +00006212static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6213 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006214 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006215}
danielk1977b4b47412007-08-17 15:53:36 +00006216#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6217 #define unixDlOpen 0
6218 #define unixDlError 0
6219 #define unixDlSym 0
6220 #define unixDlClose 0
6221#endif
6222
6223/*
danielk197790949c22007-08-17 16:50:38 +00006224** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006225*/
danielk1977397d65f2008-11-19 11:35:39 +00006226static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6227 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006228 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006229
drhbbd42a62004-05-22 17:41:58 +00006230 /* We have to initialize zBuf to prevent valgrind from reporting
6231 ** errors. The reports issued by valgrind are incorrect - we would
6232 ** prefer that the randomness be increased by making use of the
6233 ** uninitialized space in zBuf - but valgrind errors tend to worry
6234 ** some users. Rather than argue, it seems easier just to initialize
6235 ** the whole array and silence valgrind, even if that means less randomness
6236 ** in the random seed.
6237 **
6238 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006239 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006240 ** tests repeatable.
6241 */
danielk1977b4b47412007-08-17 15:53:36 +00006242 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006243 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006244#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006245 {
drhb00d8622014-01-01 15:18:36 +00006246 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006247 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006248 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006249 time_t t;
6250 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006251 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006252 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6253 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6254 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006255 }else{
drhc18b4042012-02-10 03:10:27 +00006256 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006257 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006258 }
drhbbd42a62004-05-22 17:41:58 +00006259 }
6260#endif
drh72cbd072008-10-14 17:58:38 +00006261 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006262}
6263
danielk1977b4b47412007-08-17 15:53:36 +00006264
drhbbd42a62004-05-22 17:41:58 +00006265/*
6266** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006267** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006268** The return value is the number of microseconds of sleep actually
6269** requested from the underlying operating system, a number which
6270** might be greater than or equal to the argument, but not less
6271** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006272*/
danielk1977397d65f2008-11-19 11:35:39 +00006273static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006274#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006275 struct timespec sp;
6276
6277 sp.tv_sec = microseconds / 1000000;
6278 sp.tv_nsec = (microseconds % 1000000) * 1000;
6279 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006280 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006281 return microseconds;
6282#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006283 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006284 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006285 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006286#else
danielk1977b4b47412007-08-17 15:53:36 +00006287 int seconds = (microseconds+999999)/1000000;
6288 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006289 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006290 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006291#endif
drh88f474a2006-01-02 20:00:12 +00006292}
6293
6294/*
drh6b9d6dd2008-12-03 19:34:47 +00006295** The following variable, if set to a non-zero value, is interpreted as
6296** the number of seconds since 1970 and is used to set the result of
6297** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006298*/
6299#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006300int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006301#endif
6302
6303/*
drhb7e8ea22010-05-03 14:32:30 +00006304** Find the current time (in Universal Coordinated Time). Write into *piNow
6305** the current time and date as a Julian Day number times 86_400_000. In
6306** other words, write into *piNow the number of milliseconds since the Julian
6307** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6308** proleptic Gregorian calendar.
6309**
drh31702252011-10-12 23:13:43 +00006310** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6311** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006312*/
6313static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6314 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006315 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006316#if defined(NO_GETTOD)
6317 time_t t;
6318 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006319 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006320#elif OS_VXWORKS
6321 struct timespec sNow;
6322 clock_gettime(CLOCK_REALTIME, &sNow);
6323 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6324#else
6325 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006326 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6327 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006328#endif
6329
6330#ifdef SQLITE_TEST
6331 if( sqlite3_current_time ){
6332 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6333 }
6334#endif
6335 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006336 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006337}
6338
drhc3dfa5e2016-01-22 19:44:03 +00006339#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006340/*
drhbbd42a62004-05-22 17:41:58 +00006341** Find the current time (in Universal Coordinated Time). Write the
6342** current time and date as a Julian Day number into *prNow and
6343** return 0. Return 1 if the time and date cannot be found.
6344*/
danielk1977397d65f2008-11-19 11:35:39 +00006345static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006346 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006347 int rc;
drhff828942010-06-26 21:34:06 +00006348 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006349 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006350 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006351 return rc;
drhbbd42a62004-05-22 17:41:58 +00006352}
drh5337dac2015-11-25 15:15:03 +00006353#else
6354# define unixCurrentTime 0
6355#endif
danielk1977b4b47412007-08-17 15:53:36 +00006356
drh6b9d6dd2008-12-03 19:34:47 +00006357/*
drh1b9f2142016-03-17 16:01:23 +00006358** The xGetLastError() method is designed to return a better
6359** low-level error message when operating-system problems come up
6360** during SQLite operation. Only the integer return code is currently
6361** used.
drh6b9d6dd2008-12-03 19:34:47 +00006362*/
danielk1977397d65f2008-11-19 11:35:39 +00006363static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6364 UNUSED_PARAMETER(NotUsed);
6365 UNUSED_PARAMETER(NotUsed2);
6366 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006367 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006368}
6369
drhf2424c52010-04-26 00:04:55 +00006370
6371/*
drh734c9862008-11-28 15:37:20 +00006372************************ End of sqlite3_vfs methods ***************************
6373******************************************************************************/
6374
drh715ff302008-12-03 22:32:44 +00006375/******************************************************************************
6376************************** Begin Proxy Locking ********************************
6377**
6378** Proxy locking is a "uber-locking-method" in this sense: It uses the
6379** other locking methods on secondary lock files. Proxy locking is a
6380** meta-layer over top of the primitive locking implemented above. For
6381** this reason, the division that implements of proxy locking is deferred
6382** until late in the file (here) after all of the other I/O methods have
6383** been defined - so that the primitive locking methods are available
6384** as services to help with the implementation of proxy locking.
6385**
6386****
6387**
6388** The default locking schemes in SQLite use byte-range locks on the
6389** database file to coordinate safe, concurrent access by multiple readers
6390** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6391** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6392** as POSIX read & write locks over fixed set of locations (via fsctl),
6393** on AFP and SMB only exclusive byte-range locks are available via fsctl
6394** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6395** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6396** address in the shared range is taken for a SHARED lock, the entire
6397** shared range is taken for an EXCLUSIVE lock):
6398**
drhf2f105d2012-08-20 15:53:54 +00006399** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006400** RESERVED_BYTE 0x40000001
6401** SHARED_RANGE 0x40000002 -> 0x40000200
6402**
6403** This works well on the local file system, but shows a nearly 100x
6404** slowdown in read performance on AFP because the AFP client disables
6405** the read cache when byte-range locks are present. Enabling the read
6406** cache exposes a cache coherency problem that is present on all OS X
6407** supported network file systems. NFS and AFP both observe the
6408** close-to-open semantics for ensuring cache coherency
6409** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6410** address the requirements for concurrent database access by multiple
6411** readers and writers
6412** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6413**
6414** To address the performance and cache coherency issues, proxy file locking
6415** changes the way database access is controlled by limiting access to a
6416** single host at a time and moving file locks off of the database file
6417** and onto a proxy file on the local file system.
6418**
6419**
6420** Using proxy locks
6421** -----------------
6422**
6423** C APIs
6424**
drh4bf66fd2015-02-19 02:43:02 +00006425** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006426** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006427** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6428** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006429**
6430**
6431** SQL pragmas
6432**
6433** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6434** PRAGMA [database.]lock_proxy_file
6435**
6436** Specifying ":auto:" means that if there is a conch file with a matching
6437** host ID in it, the proxy path in the conch file will be used, otherwise
6438** a proxy path based on the user's temp dir
6439** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6440** actual proxy file name is generated from the name and path of the
6441** database file. For example:
6442**
6443** For database path "/Users/me/foo.db"
6444** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6445**
6446** Once a lock proxy is configured for a database connection, it can not
6447** be removed, however it may be switched to a different proxy path via
6448** the above APIs (assuming the conch file is not being held by another
6449** connection or process).
6450**
6451**
6452** How proxy locking works
6453** -----------------------
6454**
6455** Proxy file locking relies primarily on two new supporting files:
6456**
6457** * conch file to limit access to the database file to a single host
6458** at a time
6459**
6460** * proxy file to act as a proxy for the advisory locks normally
6461** taken on the database
6462**
6463** The conch file - to use a proxy file, sqlite must first "hold the conch"
6464** by taking an sqlite-style shared lock on the conch file, reading the
6465** contents and comparing the host's unique host ID (see below) and lock
6466** proxy path against the values stored in the conch. The conch file is
6467** stored in the same directory as the database file and the file name
6468** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006469** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006470** host ID and/or proxy path, then the lock is escalated to an exclusive
6471** lock and the conch file contents is updated with the host ID and proxy
6472** path and the lock is downgraded to a shared lock again. If the conch
6473** is held by another process (with a shared lock), the exclusive lock
6474** will fail and SQLITE_BUSY is returned.
6475**
6476** The proxy file - a single-byte file used for all advisory file locks
6477** normally taken on the database file. This allows for safe sharing
6478** of the database file for multiple readers and writers on the same
6479** host (the conch ensures that they all use the same local lock file).
6480**
drh715ff302008-12-03 22:32:44 +00006481** Requesting the lock proxy does not immediately take the conch, it is
6482** only taken when the first request to lock database file is made.
6483** This matches the semantics of the traditional locking behavior, where
6484** opening a connection to a database file does not take a lock on it.
6485** The shared lock and an open file descriptor are maintained until
6486** the connection to the database is closed.
6487**
6488** The proxy file and the lock file are never deleted so they only need
6489** to be created the first time they are used.
6490**
6491** Configuration options
6492** ---------------------
6493**
6494** SQLITE_PREFER_PROXY_LOCKING
6495**
6496** Database files accessed on non-local file systems are
6497** automatically configured for proxy locking, lock files are
6498** named automatically using the same logic as
6499** PRAGMA lock_proxy_file=":auto:"
6500**
6501** SQLITE_PROXY_DEBUG
6502**
6503** Enables the logging of error messages during host id file
6504** retrieval and creation
6505**
drh715ff302008-12-03 22:32:44 +00006506** LOCKPROXYDIR
6507**
6508** Overrides the default directory used for lock proxy files that
6509** are named automatically via the ":auto:" setting
6510**
6511** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6512**
6513** Permissions to use when creating a directory for storing the
6514** lock proxy files, only used when LOCKPROXYDIR is not set.
6515**
6516**
6517** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6518** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6519** force proxy locking to be used for every database file opened, and 0
6520** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006521** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006522** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6523*/
6524
6525/*
6526** Proxy locking is only available on MacOSX
6527*/
drhd2cb50b2009-01-09 21:41:17 +00006528#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006529
drh715ff302008-12-03 22:32:44 +00006530/*
6531** The proxyLockingContext has the path and file structures for the remote
6532** and local proxy files in it
6533*/
6534typedef struct proxyLockingContext proxyLockingContext;
6535struct proxyLockingContext {
6536 unixFile *conchFile; /* Open conch file */
6537 char *conchFilePath; /* Name of the conch file */
6538 unixFile *lockProxy; /* Open proxy lock file */
6539 char *lockProxyPath; /* Name of the proxy lock file */
6540 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006541 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006542 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006543 void *oldLockingContext; /* Original lockingcontext to restore on close */
6544 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6545};
6546
drh7ed97b92010-01-20 13:07:21 +00006547/*
6548** The proxy lock file path for the database at dbPath is written into lPath,
6549** which must point to valid, writable memory large enough for a maxLen length
6550** file path.
drh715ff302008-12-03 22:32:44 +00006551*/
drh715ff302008-12-03 22:32:44 +00006552static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6553 int len;
6554 int dbLen;
6555 int i;
6556
6557#ifdef LOCKPROXYDIR
6558 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6559#else
6560# ifdef _CS_DARWIN_USER_TEMP_DIR
6561 {
drh7ed97b92010-01-20 13:07:21 +00006562 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006563 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006564 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006565 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006566 }
drh7ed97b92010-01-20 13:07:21 +00006567 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006568 }
6569# else
6570 len = strlcpy(lPath, "/tmp/", maxLen);
6571# endif
6572#endif
6573
6574 if( lPath[len-1]!='/' ){
6575 len = strlcat(lPath, "/", maxLen);
6576 }
6577
6578 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006579 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006580 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006581 char c = dbPath[i];
6582 lPath[i+len] = (c=='/')?'_':c;
6583 }
6584 lPath[i+len]='\0';
6585 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006586 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006587 return SQLITE_OK;
6588}
6589
drh7ed97b92010-01-20 13:07:21 +00006590/*
6591 ** Creates the lock file and any missing directories in lockPath
6592 */
6593static int proxyCreateLockPath(const char *lockPath){
6594 int i, len;
6595 char buf[MAXPATHLEN];
6596 int start = 0;
6597
6598 assert(lockPath!=NULL);
6599 /* try to create all the intermediate directories */
6600 len = (int)strlen(lockPath);
6601 buf[0] = lockPath[0];
6602 for( i=1; i<len; i++ ){
6603 if( lockPath[i] == '/' && (i - start > 0) ){
6604 /* only mkdir if leaf dir != "." or "/" or ".." */
6605 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6606 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6607 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006608 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006609 int err=errno;
6610 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006611 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006612 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006613 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006614 return err;
6615 }
6616 }
6617 }
6618 start=i+1;
6619 }
6620 buf[i] = lockPath[i];
6621 }
drh62aaa6c2015-11-21 17:27:42 +00006622 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006623 return 0;
6624}
6625
drh715ff302008-12-03 22:32:44 +00006626/*
6627** Create a new VFS file descriptor (stored in memory obtained from
6628** sqlite3_malloc) and open the file named "path" in the file descriptor.
6629**
6630** The caller is responsible not only for closing the file descriptor
6631** but also for freeing the memory associated with the file descriptor.
6632*/
drh7ed97b92010-01-20 13:07:21 +00006633static int proxyCreateUnixFile(
6634 const char *path, /* path for the new unixFile */
6635 unixFile **ppFile, /* unixFile created and returned by ref */
6636 int islockfile /* if non zero missing dirs will be created */
6637) {
6638 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006639 unixFile *pNew;
6640 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006641 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006642 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006643 int terrno = 0;
6644 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006645
drh7ed97b92010-01-20 13:07:21 +00006646 /* 1. first try to open/create the file
6647 ** 2. if that fails, and this is a lock file (not-conch), try creating
6648 ** the parent directories and then try again.
6649 ** 3. if that fails, try to open the file read-only
6650 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6651 */
6652 pUnused = findReusableFd(path, openFlags);
6653 if( pUnused ){
6654 fd = pUnused->fd;
6655 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006656 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006657 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006658 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006659 }
6660 }
6661 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006662 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006663 terrno = errno;
6664 if( fd<0 && errno==ENOENT && islockfile ){
6665 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006666 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006667 }
6668 }
6669 }
6670 if( fd<0 ){
6671 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006672 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006673 terrno = errno;
6674 }
6675 if( fd<0 ){
6676 if( islockfile ){
6677 return SQLITE_BUSY;
6678 }
6679 switch (terrno) {
6680 case EACCES:
6681 return SQLITE_PERM;
6682 case EIO:
6683 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6684 default:
drh9978c972010-02-23 17:36:32 +00006685 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006686 }
6687 }
6688
drhf3cdcdc2015-04-29 16:50:28 +00006689 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006690 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006691 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006692 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006693 }
6694 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006695 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006696 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006697 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006698 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006699 pUnused->fd = fd;
6700 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006701 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006702
drhc02a43a2012-01-10 23:18:38 +00006703 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006704 if( rc==SQLITE_OK ){
6705 *ppFile = pNew;
6706 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006707 }
drh7ed97b92010-01-20 13:07:21 +00006708end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006709 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006710 sqlite3_free(pNew);
6711 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006712 return rc;
6713}
6714
drh7ed97b92010-01-20 13:07:21 +00006715#ifdef SQLITE_TEST
6716/* simulate multiple hosts by creating unique hostid file paths */
6717int sqlite3_hostid_num = 0;
6718#endif
6719
6720#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6721
drh6bca6512015-04-13 23:05:28 +00006722#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006723/* Not always defined in the headers as it ought to be */
6724extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006725#endif
drh0ab216a2010-07-02 17:10:40 +00006726
drh7ed97b92010-01-20 13:07:21 +00006727/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6728** bytes of writable memory.
6729*/
6730static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006731 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6732 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006733#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006734 {
drh4bf66fd2015-02-19 02:43:02 +00006735 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006736 if( gethostuuid(pHostID, &timeout) ){
6737 int err = errno;
6738 if( pError ){
6739 *pError = err;
6740 }
6741 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006742 }
drh7ed97b92010-01-20 13:07:21 +00006743 }
drh3d4435b2011-08-26 20:55:50 +00006744#else
6745 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006746#endif
drh7ed97b92010-01-20 13:07:21 +00006747#ifdef SQLITE_TEST
6748 /* simulate multiple hosts by creating unique hostid file paths */
6749 if( sqlite3_hostid_num != 0){
6750 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6751 }
6752#endif
6753
6754 return SQLITE_OK;
6755}
6756
6757/* The conch file contains the header, host id and lock file path
6758 */
6759#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6760#define PROXY_HEADERLEN 1 /* conch file header length */
6761#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6762#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6763
6764/*
6765** Takes an open conch file, copies the contents to a new path and then moves
6766** it back. The newly created file's file descriptor is assigned to the
6767** conch file structure and finally the original conch file descriptor is
6768** closed. Returns zero if successful.
6769*/
6770static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6771 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6772 unixFile *conchFile = pCtx->conchFile;
6773 char tPath[MAXPATHLEN];
6774 char buf[PROXY_MAXCONCHLEN];
6775 char *cPath = pCtx->conchFilePath;
6776 size_t readLen = 0;
6777 size_t pathLen = 0;
6778 char errmsg[64] = "";
6779 int fd = -1;
6780 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006781 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006782
6783 /* create a new path by replace the trailing '-conch' with '-break' */
6784 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6785 if( pathLen>MAXPATHLEN || pathLen<6 ||
6786 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006787 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006788 goto end_breaklock;
6789 }
6790 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006791 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006792 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006793 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006794 goto end_breaklock;
6795 }
6796 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006797 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006798 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006799 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006800 goto end_breaklock;
6801 }
drhe562be52011-03-02 18:01:10 +00006802 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006803 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006804 goto end_breaklock;
6805 }
6806 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006807 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006808 goto end_breaklock;
6809 }
6810 rc = 0;
6811 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006812 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006813 conchFile->h = fd;
6814 conchFile->openFlags = O_RDWR | O_CREAT;
6815
6816end_breaklock:
6817 if( rc ){
6818 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006819 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006820 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006821 }
6822 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6823 }
6824 return rc;
6825}
6826
6827/* Take the requested lock on the conch file and break a stale lock if the
6828** host id matches.
6829*/
6830static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6831 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6832 unixFile *conchFile = pCtx->conchFile;
6833 int rc = SQLITE_OK;
6834 int nTries = 0;
6835 struct timespec conchModTime;
6836
drh3d4435b2011-08-26 20:55:50 +00006837 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006838 do {
6839 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6840 nTries ++;
6841 if( rc==SQLITE_BUSY ){
6842 /* If the lock failed (busy):
6843 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6844 * 2nd try: fail if the mod time changed or host id is different, wait
6845 * 10 sec and try again
6846 * 3rd try: break the lock unless the mod time has changed.
6847 */
6848 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006849 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006850 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006851 return SQLITE_IOERR_LOCK;
6852 }
6853
6854 if( nTries==1 ){
6855 conchModTime = buf.st_mtimespec;
6856 usleep(500000); /* wait 0.5 sec and try the lock again*/
6857 continue;
6858 }
6859
6860 assert( nTries>1 );
6861 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6862 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6863 return SQLITE_BUSY;
6864 }
6865
6866 if( nTries==2 ){
6867 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006868 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006869 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006870 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006871 return SQLITE_IOERR_LOCK;
6872 }
6873 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6874 /* don't break the lock if the host id doesn't match */
6875 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6876 return SQLITE_BUSY;
6877 }
6878 }else{
6879 /* don't break the lock on short read or a version mismatch */
6880 return SQLITE_BUSY;
6881 }
6882 usleep(10000000); /* wait 10 sec and try the lock again */
6883 continue;
6884 }
6885
6886 assert( nTries==3 );
6887 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6888 rc = SQLITE_OK;
6889 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006890 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006891 }
6892 if( !rc ){
6893 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6894 }
6895 }
6896 }
6897 } while( rc==SQLITE_BUSY && nTries<3 );
6898
6899 return rc;
6900}
6901
6902/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006903** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6904** lockPath means that the lockPath in the conch file will be used if the
6905** host IDs match, or a new lock path will be generated automatically
6906** and written to the conch file.
6907*/
6908static int proxyTakeConch(unixFile *pFile){
6909 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6910
drh7ed97b92010-01-20 13:07:21 +00006911 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006912 return SQLITE_OK;
6913 }else{
6914 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006915 uuid_t myHostID;
6916 int pError = 0;
6917 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006918 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006919 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006920 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006921 int createConch = 0;
6922 int hostIdMatch = 0;
6923 int readLen = 0;
6924 int tryOldLockPath = 0;
6925 int forceNewLockPath = 0;
6926
drh308c2a52010-05-14 11:30:18 +00006927 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006928 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006929 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006930
drh7ed97b92010-01-20 13:07:21 +00006931 rc = proxyGetHostID(myHostID, &pError);
6932 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006933 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006934 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006935 }
drh7ed97b92010-01-20 13:07:21 +00006936 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006937 if( rc!=SQLITE_OK ){
6938 goto end_takeconch;
6939 }
drh7ed97b92010-01-20 13:07:21 +00006940 /* read the existing conch file */
6941 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6942 if( readLen<0 ){
6943 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006944 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006945 rc = SQLITE_IOERR_READ;
6946 goto end_takeconch;
6947 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6948 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6949 /* a short read or version format mismatch means we need to create a new
6950 ** conch file.
6951 */
6952 createConch = 1;
6953 }
6954 /* if the host id matches and the lock path already exists in the conch
6955 ** we'll try to use the path there, if we can't open that path, we'll
6956 ** retry with a new auto-generated path
6957 */
6958 do { /* in case we need to try again for an :auto: named lock file */
6959
6960 if( !createConch && !forceNewLockPath ){
6961 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6962 PROXY_HOSTIDLEN);
6963 /* if the conch has data compare the contents */
6964 if( !pCtx->lockProxyPath ){
6965 /* for auto-named local lock file, just check the host ID and we'll
6966 ** use the local lock file path that's already in there
6967 */
6968 if( hostIdMatch ){
6969 size_t pathLen = (readLen - PROXY_PATHINDEX);
6970
6971 if( pathLen>=MAXPATHLEN ){
6972 pathLen=MAXPATHLEN-1;
6973 }
6974 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6975 lockPath[pathLen] = 0;
6976 tempLockPath = lockPath;
6977 tryOldLockPath = 1;
6978 /* create a copy of the lock path if the conch is taken */
6979 goto end_takeconch;
6980 }
6981 }else if( hostIdMatch
6982 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6983 readLen-PROXY_PATHINDEX)
6984 ){
6985 /* conch host and lock path match */
6986 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006987 }
drh7ed97b92010-01-20 13:07:21 +00006988 }
6989
6990 /* if the conch isn't writable and doesn't match, we can't take it */
6991 if( (conchFile->openFlags&O_RDWR) == 0 ){
6992 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006993 goto end_takeconch;
6994 }
drh7ed97b92010-01-20 13:07:21 +00006995
6996 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006997 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006998 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6999 tempLockPath = lockPath;
7000 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007001 }
drh7ed97b92010-01-20 13:07:21 +00007002
7003 /* update conch with host and path (this will fail if other process
7004 ** has a shared lock already), if the host id matches, use the big
7005 ** stick.
drh715ff302008-12-03 22:32:44 +00007006 */
drh7ed97b92010-01-20 13:07:21 +00007007 futimes(conchFile->h, NULL);
7008 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007009 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007010 /* We are trying for an exclusive lock but another thread in this
7011 ** same process is still holding a shared lock. */
7012 rc = SQLITE_BUSY;
7013 } else {
7014 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007015 }
drh715ff302008-12-03 22:32:44 +00007016 }else{
drh4bf66fd2015-02-19 02:43:02 +00007017 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007018 }
drh7ed97b92010-01-20 13:07:21 +00007019 if( rc==SQLITE_OK ){
7020 char writeBuffer[PROXY_MAXCONCHLEN];
7021 int writeSize = 0;
7022
7023 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7024 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7025 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007026 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7027 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007028 }else{
7029 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7030 }
7031 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007032 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007033 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007034 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007035 /* If we created a new conch file (not just updated the contents of a
7036 ** valid conch file), try to match the permissions of the database
7037 */
7038 if( rc==SQLITE_OK && createConch ){
7039 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007040 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007041 if( err==0 ){
7042 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7043 S_IROTH|S_IWOTH);
7044 /* try to match the database file R/W permissions, ignore failure */
7045#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007046 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007047#else
drhff812312011-02-23 13:33:46 +00007048 do{
drhe562be52011-03-02 18:01:10 +00007049 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007050 }while( rc==(-1) && errno==EINTR );
7051 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007052 int code = errno;
7053 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7054 cmode, code, strerror(code));
7055 } else {
7056 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7057 }
7058 }else{
7059 int code = errno;
7060 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7061 err, code, strerror(code));
7062#endif
7063 }
drh715ff302008-12-03 22:32:44 +00007064 }
7065 }
drh7ed97b92010-01-20 13:07:21 +00007066 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7067
7068 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007069 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007070 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007071 int fd;
drh7ed97b92010-01-20 13:07:21 +00007072 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007073 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007074 }
7075 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007076 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007077 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007078 if( fd>=0 ){
7079 pFile->h = fd;
7080 }else{
drh9978c972010-02-23 17:36:32 +00007081 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007082 during locking */
7083 }
7084 }
7085 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7086 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7087 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7088 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7089 /* we couldn't create the proxy lock file with the old lock file path
7090 ** so try again via auto-naming
7091 */
7092 forceNewLockPath = 1;
7093 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007094 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007095 }
7096 }
7097 if( rc==SQLITE_OK ){
7098 /* Need to make a copy of path if we extracted the value
7099 ** from the conch file or the path was allocated on the stack
7100 */
7101 if( tempLockPath ){
7102 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7103 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007104 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007105 }
7106 }
7107 }
7108 if( rc==SQLITE_OK ){
7109 pCtx->conchHeld = 1;
7110
7111 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7112 afpLockingContext *afpCtx;
7113 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7114 afpCtx->dbPath = pCtx->lockProxyPath;
7115 }
7116 } else {
7117 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7118 }
drh308c2a52010-05-14 11:30:18 +00007119 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7120 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007121 return rc;
drh308c2a52010-05-14 11:30:18 +00007122 } while (1); /* in case we need to retry the :auto: lock file -
7123 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007124 }
7125}
7126
7127/*
7128** If pFile holds a lock on a conch file, then release that lock.
7129*/
7130static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007131 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007132 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7133 unixFile *conchFile; /* Name of the conch file */
7134
7135 pCtx = (proxyLockingContext *)pFile->lockingContext;
7136 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007137 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007138 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007139 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007140 if( pCtx->conchHeld>0 ){
7141 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7142 }
drh715ff302008-12-03 22:32:44 +00007143 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007144 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7145 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007146 return rc;
7147}
7148
7149/*
7150** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007151** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007152** Make *pConchPath point to the new name. Return SQLITE_OK on success
7153** or SQLITE_NOMEM if unable to obtain memory.
7154**
7155** The caller is responsible for ensuring that the allocated memory
7156** space is eventually freed.
7157**
7158** *pConchPath is set to NULL if a memory allocation error occurs.
7159*/
7160static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7161 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007162 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007163 char *conchPath; /* buffer in which to construct conch name */
7164
7165 /* Allocate space for the conch filename and initialize the name to
7166 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007167 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007168 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007169 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007170 }
7171 memcpy(conchPath, dbPath, len+1);
7172
7173 /* now insert a "." before the last / character */
7174 for( i=(len-1); i>=0; i-- ){
7175 if( conchPath[i]=='/' ){
7176 i++;
7177 break;
7178 }
7179 }
7180 conchPath[i]='.';
7181 while ( i<len ){
7182 conchPath[i+1]=dbPath[i];
7183 i++;
7184 }
7185
7186 /* append the "-conch" suffix to the file */
7187 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007188 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007189
7190 return SQLITE_OK;
7191}
7192
7193
7194/* Takes a fully configured proxy locking-style unix file and switches
7195** the local lock file path
7196*/
7197static int switchLockProxyPath(unixFile *pFile, const char *path) {
7198 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7199 char *oldPath = pCtx->lockProxyPath;
7200 int rc = SQLITE_OK;
7201
drh308c2a52010-05-14 11:30:18 +00007202 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007203 return SQLITE_BUSY;
7204 }
7205
7206 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7207 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7208 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7209 return SQLITE_OK;
7210 }else{
7211 unixFile *lockProxy = pCtx->lockProxy;
7212 pCtx->lockProxy=NULL;
7213 pCtx->conchHeld = 0;
7214 if( lockProxy!=NULL ){
7215 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7216 if( rc ) return rc;
7217 sqlite3_free(lockProxy);
7218 }
7219 sqlite3_free(oldPath);
7220 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7221 }
7222
7223 return rc;
7224}
7225
7226/*
7227** pFile is a file that has been opened by a prior xOpen call. dbPath
7228** is a string buffer at least MAXPATHLEN+1 characters in size.
7229**
7230** This routine find the filename associated with pFile and writes it
7231** int dbPath.
7232*/
7233static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007234#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007235 if( pFile->pMethod == &afpIoMethods ){
7236 /* afp style keeps a reference to the db path in the filePath field
7237 ** of the struct */
drhea678832008-12-10 19:26:22 +00007238 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007239 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7240 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007241 } else
drh715ff302008-12-03 22:32:44 +00007242#endif
7243 if( pFile->pMethod == &dotlockIoMethods ){
7244 /* dot lock style uses the locking context to store the dot lock
7245 ** file path */
7246 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7247 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7248 }else{
7249 /* all other styles use the locking context to store the db file path */
7250 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007251 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007252 }
7253 return SQLITE_OK;
7254}
7255
7256/*
7257** Takes an already filled in unix file and alters it so all file locking
7258** will be performed on the local proxy lock file. The following fields
7259** are preserved in the locking context so that they can be restored and
7260** the unix structure properly cleaned up at close time:
7261** ->lockingContext
7262** ->pMethod
7263*/
7264static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7265 proxyLockingContext *pCtx;
7266 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7267 char *lockPath=NULL;
7268 int rc = SQLITE_OK;
7269
drh308c2a52010-05-14 11:30:18 +00007270 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007271 return SQLITE_BUSY;
7272 }
7273 proxyGetDbPathForUnixFile(pFile, dbPath);
7274 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7275 lockPath=NULL;
7276 }else{
7277 lockPath=(char *)path;
7278 }
7279
drh308c2a52010-05-14 11:30:18 +00007280 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007281 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007282
drhf3cdcdc2015-04-29 16:50:28 +00007283 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007284 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007285 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007286 }
7287 memset(pCtx, 0, sizeof(*pCtx));
7288
7289 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7290 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007291 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7292 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7293 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7294 ** (c) the file system is read-only, then enable no-locking access.
7295 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7296 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7297 */
7298 struct statfs fsInfo;
7299 struct stat conchInfo;
7300 int goLockless = 0;
7301
drh99ab3b12011-03-02 15:09:07 +00007302 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007303 int err = errno;
7304 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7305 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7306 }
7307 }
7308 if( goLockless ){
7309 pCtx->conchHeld = -1; /* read only FS/ lockless */
7310 rc = SQLITE_OK;
7311 }
7312 }
drh715ff302008-12-03 22:32:44 +00007313 }
7314 if( rc==SQLITE_OK && lockPath ){
7315 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7316 }
7317
7318 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007319 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7320 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007321 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007322 }
7323 }
7324 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007325 /* all memory is allocated, proxys are created and assigned,
7326 ** switch the locking context and pMethod then return.
7327 */
drh715ff302008-12-03 22:32:44 +00007328 pCtx->oldLockingContext = pFile->lockingContext;
7329 pFile->lockingContext = pCtx;
7330 pCtx->pOldMethod = pFile->pMethod;
7331 pFile->pMethod = &proxyIoMethods;
7332 }else{
7333 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007334 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007335 sqlite3_free(pCtx->conchFile);
7336 }
drhd56b1212010-08-11 06:14:15 +00007337 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007338 sqlite3_free(pCtx->conchFilePath);
7339 sqlite3_free(pCtx);
7340 }
drh308c2a52010-05-14 11:30:18 +00007341 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7342 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007343 return rc;
7344}
7345
7346
7347/*
7348** This routine handles sqlite3_file_control() calls that are specific
7349** to proxy locking.
7350*/
7351static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7352 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007353 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007354 unixFile *pFile = (unixFile*)id;
7355 if( pFile->pMethod == &proxyIoMethods ){
7356 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7357 proxyTakeConch(pFile);
7358 if( pCtx->lockProxyPath ){
7359 *(const char **)pArg = pCtx->lockProxyPath;
7360 }else{
7361 *(const char **)pArg = ":auto: (not held)";
7362 }
7363 } else {
7364 *(const char **)pArg = NULL;
7365 }
7366 return SQLITE_OK;
7367 }
drh4bf66fd2015-02-19 02:43:02 +00007368 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007369 unixFile *pFile = (unixFile*)id;
7370 int rc = SQLITE_OK;
7371 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7372 if( pArg==NULL || (const char *)pArg==0 ){
7373 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007374 /* turn off proxy locking - not supported. If support is added for
7375 ** switching proxy locking mode off then it will need to fail if
7376 ** the journal mode is WAL mode.
7377 */
drh715ff302008-12-03 22:32:44 +00007378 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7379 }else{
7380 /* turn off proxy locking - already off - NOOP */
7381 rc = SQLITE_OK;
7382 }
7383 }else{
7384 const char *proxyPath = (const char *)pArg;
7385 if( isProxyStyle ){
7386 proxyLockingContext *pCtx =
7387 (proxyLockingContext*)pFile->lockingContext;
7388 if( !strcmp(pArg, ":auto:")
7389 || (pCtx->lockProxyPath &&
7390 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7391 ){
7392 rc = SQLITE_OK;
7393 }else{
7394 rc = switchLockProxyPath(pFile, proxyPath);
7395 }
7396 }else{
7397 /* turn on proxy file locking */
7398 rc = proxyTransformUnixFile(pFile, proxyPath);
7399 }
7400 }
7401 return rc;
7402 }
7403 default: {
7404 assert( 0 ); /* The call assures that only valid opcodes are sent */
7405 }
7406 }
7407 /*NOTREACHED*/
7408 return SQLITE_ERROR;
7409}
7410
7411/*
7412** Within this division (the proxying locking implementation) the procedures
7413** above this point are all utilities. The lock-related methods of the
7414** proxy-locking sqlite3_io_method object follow.
7415*/
7416
7417
7418/*
7419** This routine checks if there is a RESERVED lock held on the specified
7420** file by this or any other process. If such a lock is held, set *pResOut
7421** to a non-zero value otherwise *pResOut is set to zero. The return value
7422** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7423*/
7424static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7425 unixFile *pFile = (unixFile*)id;
7426 int rc = proxyTakeConch(pFile);
7427 if( rc==SQLITE_OK ){
7428 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007429 if( pCtx->conchHeld>0 ){
7430 unixFile *proxy = pCtx->lockProxy;
7431 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7432 }else{ /* conchHeld < 0 is lockless */
7433 pResOut=0;
7434 }
drh715ff302008-12-03 22:32:44 +00007435 }
7436 return rc;
7437}
7438
7439/*
drh308c2a52010-05-14 11:30:18 +00007440** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007441** of the following:
7442**
7443** (1) SHARED_LOCK
7444** (2) RESERVED_LOCK
7445** (3) PENDING_LOCK
7446** (4) EXCLUSIVE_LOCK
7447**
7448** Sometimes when requesting one lock state, additional lock states
7449** are inserted in between. The locking might fail on one of the later
7450** transitions leaving the lock state different from what it started but
7451** still short of its goal. The following chart shows the allowed
7452** transitions and the inserted intermediate states:
7453**
7454** UNLOCKED -> SHARED
7455** SHARED -> RESERVED
7456** SHARED -> (PENDING) -> EXCLUSIVE
7457** RESERVED -> (PENDING) -> EXCLUSIVE
7458** PENDING -> EXCLUSIVE
7459**
7460** This routine will only increase a lock. Use the sqlite3OsUnlock()
7461** routine to lower a locking level.
7462*/
drh308c2a52010-05-14 11:30:18 +00007463static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007464 unixFile *pFile = (unixFile*)id;
7465 int rc = proxyTakeConch(pFile);
7466 if( rc==SQLITE_OK ){
7467 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007468 if( pCtx->conchHeld>0 ){
7469 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007470 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7471 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007472 }else{
7473 /* conchHeld < 0 is lockless */
7474 }
drh715ff302008-12-03 22:32:44 +00007475 }
7476 return rc;
7477}
7478
7479
7480/*
drh308c2a52010-05-14 11:30:18 +00007481** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007482** must be either NO_LOCK or SHARED_LOCK.
7483**
7484** If the locking level of the file descriptor is already at or below
7485** the requested locking level, this routine is a no-op.
7486*/
drh308c2a52010-05-14 11:30:18 +00007487static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007488 unixFile *pFile = (unixFile*)id;
7489 int rc = proxyTakeConch(pFile);
7490 if( rc==SQLITE_OK ){
7491 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007492 if( pCtx->conchHeld>0 ){
7493 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007494 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7495 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007496 }else{
7497 /* conchHeld < 0 is lockless */
7498 }
drh715ff302008-12-03 22:32:44 +00007499 }
7500 return rc;
7501}
7502
7503/*
7504** Close a file that uses proxy locks.
7505*/
7506static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007507 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007508 unixFile *pFile = (unixFile*)id;
7509 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7510 unixFile *lockProxy = pCtx->lockProxy;
7511 unixFile *conchFile = pCtx->conchFile;
7512 int rc = SQLITE_OK;
7513
7514 if( lockProxy ){
7515 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7516 if( rc ) return rc;
7517 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7518 if( rc ) return rc;
7519 sqlite3_free(lockProxy);
7520 pCtx->lockProxy = 0;
7521 }
7522 if( conchFile ){
7523 if( pCtx->conchHeld ){
7524 rc = proxyReleaseConch(pFile);
7525 if( rc ) return rc;
7526 }
7527 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7528 if( rc ) return rc;
7529 sqlite3_free(conchFile);
7530 }
drhd56b1212010-08-11 06:14:15 +00007531 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007532 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007533 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007534 /* restore the original locking context and pMethod then close it */
7535 pFile->lockingContext = pCtx->oldLockingContext;
7536 pFile->pMethod = pCtx->pOldMethod;
7537 sqlite3_free(pCtx);
7538 return pFile->pMethod->xClose(id);
7539 }
7540 return SQLITE_OK;
7541}
7542
7543
7544
drhd2cb50b2009-01-09 21:41:17 +00007545#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007546/*
7547** The proxy locking style is intended for use with AFP filesystems.
7548** And since AFP is only supported on MacOSX, the proxy locking is also
7549** restricted to MacOSX.
7550**
7551**
7552******************* End of the proxy lock implementation **********************
7553******************************************************************************/
7554
drh734c9862008-11-28 15:37:20 +00007555/*
danielk1977e339d652008-06-28 11:23:00 +00007556** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007557**
7558** This routine registers all VFS implementations for unix-like operating
7559** systems. This routine, and the sqlite3_os_end() routine that follows,
7560** should be the only routines in this file that are visible from other
7561** files.
drh6b9d6dd2008-12-03 19:34:47 +00007562**
7563** This routine is called once during SQLite initialization and by a
7564** single thread. The memory allocation and mutex subsystems have not
7565** necessarily been initialized when this routine is called, and so they
7566** should not be used.
drh153c62c2007-08-24 03:51:33 +00007567*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007568int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007569 /*
7570 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007571 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7572 ** to the "finder" function. (pAppData is a pointer to a pointer because
7573 ** silly C90 rules prohibit a void* from being cast to a function pointer
7574 ** and so we have to go through the intermediate pointer to avoid problems
7575 ** when compiling with -pedantic-errors on GCC.)
7576 **
7577 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007578 ** finder-function. The finder-function returns a pointer to the
7579 ** sqlite_io_methods object that implements the desired locking
7580 ** behaviors. See the division above that contains the IOMETHODS
7581 ** macro for addition information on finder-functions.
7582 **
7583 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7584 ** object. But the "autolockIoFinder" available on MacOSX does a little
7585 ** more than that; it looks at the filesystem type that hosts the
7586 ** database file and tries to choose an locking method appropriate for
7587 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007588 */
drh7708e972008-11-29 00:56:52 +00007589 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007590 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007591 sizeof(unixFile), /* szOsFile */ \
7592 MAX_PATHNAME, /* mxPathname */ \
7593 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007594 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007595 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007596 unixOpen, /* xOpen */ \
7597 unixDelete, /* xDelete */ \
7598 unixAccess, /* xAccess */ \
7599 unixFullPathname, /* xFullPathname */ \
7600 unixDlOpen, /* xDlOpen */ \
7601 unixDlError, /* xDlError */ \
7602 unixDlSym, /* xDlSym */ \
7603 unixDlClose, /* xDlClose */ \
7604 unixRandomness, /* xRandomness */ \
7605 unixSleep, /* xSleep */ \
7606 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007607 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007608 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007609 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007610 unixGetSystemCall, /* xGetSystemCall */ \
7611 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007612 }
7613
drh6b9d6dd2008-12-03 19:34:47 +00007614 /*
7615 ** All default VFSes for unix are contained in the following array.
7616 **
7617 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7618 ** by the SQLite core when the VFS is registered. So the following
7619 ** array cannot be const.
7620 */
danielk1977e339d652008-06-28 11:23:00 +00007621 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007622#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007623 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007624#elif OS_VXWORKS
7625 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007626#else
7627 UNIXVFS("unix", posixIoFinder ),
7628#endif
7629 UNIXVFS("unix-none", nolockIoFinder ),
7630 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007631 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007632#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007633 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007634#endif
drhe89b2912015-03-03 20:42:01 +00007635#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007636 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007637#endif
drhe89b2912015-03-03 20:42:01 +00007638#if SQLITE_ENABLE_LOCKING_STYLE
7639 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007640#endif
drhd2cb50b2009-01-09 21:41:17 +00007641#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007642 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007643 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007644 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007645#endif
drh153c62c2007-08-24 03:51:33 +00007646 };
drh6b9d6dd2008-12-03 19:34:47 +00007647 unsigned int i; /* Loop counter */
7648
drh2aa5a002011-04-13 13:42:25 +00007649 /* Double-check that the aSyscall[] array has been constructed
7650 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007651 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007652
drh6b9d6dd2008-12-03 19:34:47 +00007653 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007654 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007655 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007656 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007657 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007658}
danielk1977e339d652008-06-28 11:23:00 +00007659
7660/*
drh6b9d6dd2008-12-03 19:34:47 +00007661** Shutdown the operating system interface.
7662**
7663** Some operating systems might need to do some cleanup in this routine,
7664** to release dynamically allocated objects. But not on unix.
7665** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007666*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007667int sqlite3_os_end(void){
7668 return SQLITE_OK;
7669}
drhdce8bdb2007-08-16 13:01:44 +00007670
danielk197729bafea2008-06-26 10:41:19 +00007671#endif /* SQLITE_OS_UNIX */