blob: 99a06279f3632d6f56eed148816e928180cace3f [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 */
213 UnixUnusedFd *pUnused; /* 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*/
drhd91c68f2010-05-14 14:52:25 +00001123static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001124
drh5fdae772004-06-29 03:29:00 +00001125/*
dane18d4952011-02-21 11:46:24 +00001126**
drhaaeaa182015-11-24 15:12:47 +00001127** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001128** unixLogError().
1129**
1130** It is invoked after an error occurs in an OS function and errno has been
1131** set. It logs a message using sqlite3_log() containing the current value of
1132** errno and, if possible, the human-readable equivalent from strerror() or
1133** strerror_r().
1134**
1135** The first argument passed to the macro should be the error code that
1136** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1137** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001138** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001139** if any.
1140*/
drh0e9365c2011-03-02 02:08:13 +00001141#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1142static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001143 int errcode, /* SQLite error code */
1144 const char *zFunc, /* Name of OS function that failed */
1145 const char *zPath, /* File path associated with error */
1146 int iLine /* Source line number where error occurred */
1147){
1148 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001149 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001150
1151 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1152 ** the strerror() function to obtain the human-readable error message
1153 ** equivalent to errno. Otherwise, use strerror_r().
1154 */
1155#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1156 char aErr[80];
1157 memset(aErr, 0, sizeof(aErr));
1158 zErr = aErr;
1159
1160 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001161 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001162 ** returns a pointer to a buffer containing the error message. That pointer
1163 ** may point to aErr[], or it may point to some static storage somewhere.
1164 ** Otherwise, assume that the system provides the POSIX version of
1165 ** strerror_r(), which always writes an error message into aErr[].
1166 **
1167 ** If the code incorrectly assumes that it is the POSIX version that is
1168 ** available, the error message will often be an empty string. Not a
1169 ** huge problem. Incorrectly concluding that the GNU version is available
1170 ** could lead to a segfault though.
1171 */
1172#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1173 zErr =
1174# endif
drh0e9365c2011-03-02 02:08:13 +00001175 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001176
1177#elif SQLITE_THREADSAFE
1178 /* This is a threadsafe build, but strerror_r() is not available. */
1179 zErr = "";
1180#else
1181 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001182 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001183#endif
1184
drh0e9365c2011-03-02 02:08:13 +00001185 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001186 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001187 "os_unix.c:%d: (%d) %s(%s) - %s",
1188 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001189 );
1190
1191 return errcode;
1192}
1193
drh0e9365c2011-03-02 02:08:13 +00001194/*
1195** Close a file descriptor.
1196**
1197** We assume that close() almost always works, since it is only in a
1198** very sick application or on a very sick platform that it might fail.
1199** If it does fail, simply leak the file descriptor, but do log the
1200** error.
1201**
1202** Note that it is not safe to retry close() after EINTR since the
1203** file descriptor might have already been reused by another thread.
1204** So we don't even try to recover from an EINTR. Just log the error
1205** and move on.
1206*/
1207static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001208 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001209 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1210 pFile ? pFile->zPath : 0, lineno);
1211 }
1212}
dane18d4952011-02-21 11:46:24 +00001213
1214/*
drhe6d41732015-02-21 00:49:00 +00001215** Set the pFile->lastErrno. Do this in a subroutine as that provides
1216** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001217*/
1218static void storeLastErrno(unixFile *pFile, int error){
1219 pFile->lastErrno = error;
1220}
1221
1222/*
danb0ac3e32010-06-16 10:55:42 +00001223** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001224*/
drh0e9365c2011-03-02 02:08:13 +00001225static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001226 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001227 UnixUnusedFd *p;
1228 UnixUnusedFd *pNext;
1229 for(p=pInode->pUnused; p; p=pNext){
1230 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001231 robust_close(pFile, p->fd, __LINE__);
1232 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001233 }
drh0e9365c2011-03-02 02:08:13 +00001234 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001235}
1236
1237/*
drh8af6c222010-05-14 12:43:01 +00001238** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001239**
1240** The mutex entered using the unixEnterMutex() function must be held
1241** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001242*/
danb0ac3e32010-06-16 10:55:42 +00001243static void releaseInodeInfo(unixFile *pFile){
1244 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001245 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001246 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001247 pInode->nRef--;
1248 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001249 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001250 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001251 if( pInode->pPrev ){
1252 assert( pInode->pPrev->pNext==pInode );
1253 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001254 }else{
drh8af6c222010-05-14 12:43:01 +00001255 assert( inodeList==pInode );
1256 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001257 }
drh8af6c222010-05-14 12:43:01 +00001258 if( pInode->pNext ){
1259 assert( pInode->pNext->pPrev==pInode );
1260 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001261 }
drh8af6c222010-05-14 12:43:01 +00001262 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001263 }
drhbbd42a62004-05-22 17:41:58 +00001264 }
1265}
1266
1267/*
drh8af6c222010-05-14 12:43:01 +00001268** Given a file descriptor, locate the unixInodeInfo object that
1269** describes that file descriptor. Create a new one if necessary. The
1270** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001271**
dan9359c7b2009-08-21 08:29:10 +00001272** The mutex entered using the unixEnterMutex() function must be held
1273** when this function is called.
1274**
drh6c7d5c52008-11-21 20:32:33 +00001275** Return an appropriate error code.
1276*/
drh8af6c222010-05-14 12:43:01 +00001277static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001278 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001279 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001280){
1281 int rc; /* System call return code */
1282 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001283 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1284 struct stat statbuf; /* Low-level file information */
1285 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001286
dan9359c7b2009-08-21 08:29:10 +00001287 assert( unixMutexHeld() );
1288
drh6c7d5c52008-11-21 20:32:33 +00001289 /* Get low-level information about the file that we can used to
1290 ** create a unique name for the file.
1291 */
1292 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001293 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001294 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001295 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001296#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001297 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1298#endif
1299 return SQLITE_IOERR;
1300 }
1301
drheb0d74f2009-02-03 15:27:02 +00001302#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001303 /* On OS X on an msdos filesystem, the inode number is reported
1304 ** incorrectly for zero-size files. See ticket #3260. To work
1305 ** around this problem (we consider it a bug in OS X, not SQLite)
1306 ** we always increase the file size to 1 by writing a single byte
1307 ** prior to accessing the inode number. The one byte written is
1308 ** an ASCII 'S' character which also happens to be the first byte
1309 ** in the header of every SQLite database. In this way, if there
1310 ** is a race condition such that another thread has already populated
1311 ** the first page of the database, no damage is done.
1312 */
drh7ed97b92010-01-20 13:07:21 +00001313 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001314 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001315 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001316 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001317 return SQLITE_IOERR;
1318 }
drh99ab3b12011-03-02 15:09:07 +00001319 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001320 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001321 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001322 return SQLITE_IOERR;
1323 }
1324 }
drheb0d74f2009-02-03 15:27:02 +00001325#endif
drh6c7d5c52008-11-21 20:32:33 +00001326
drh8af6c222010-05-14 12:43:01 +00001327 memset(&fileId, 0, sizeof(fileId));
1328 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001329#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001330 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001331#else
drh25ef7f52016-12-05 20:06:45 +00001332 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001333#endif
drh8af6c222010-05-14 12:43:01 +00001334 pInode = inodeList;
1335 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1336 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001337 }
drh8af6c222010-05-14 12:43:01 +00001338 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001339 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001340 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001341 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001342 }
drh8af6c222010-05-14 12:43:01 +00001343 memset(pInode, 0, sizeof(*pInode));
1344 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1345 pInode->nRef = 1;
1346 pInode->pNext = inodeList;
1347 pInode->pPrev = 0;
1348 if( inodeList ) inodeList->pPrev = pInode;
1349 inodeList = pInode;
1350 }else{
1351 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001352 }
drh8af6c222010-05-14 12:43:01 +00001353 *ppInode = pInode;
1354 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001355}
drh6c7d5c52008-11-21 20:32:33 +00001356
drhb959a012013-12-07 12:29:22 +00001357/*
1358** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1359*/
1360static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001361#if OS_VXWORKS
1362 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1363#else
drhb959a012013-12-07 12:29:22 +00001364 struct stat buf;
1365 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001366 (osStat(pFile->zPath, &buf)!=0
1367 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001368#endif
drhb959a012013-12-07 12:29:22 +00001369}
1370
aswift5b1a2562008-08-22 00:22:35 +00001371
1372/*
drhfbc7e882013-04-11 01:16:15 +00001373** Check a unixFile that is a database. Verify the following:
1374**
1375** (1) There is exactly one hard link on the file
1376** (2) The file is not a symbolic link
1377** (3) The file has not been renamed or unlinked
1378**
1379** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1380*/
1381static void verifyDbFile(unixFile *pFile){
1382 struct stat buf;
1383 int rc;
drh86151e82015-12-08 14:37:16 +00001384
1385 /* These verifications occurs for the main database only */
1386 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1387
drhfbc7e882013-04-11 01:16:15 +00001388 rc = osFstat(pFile->h, &buf);
1389 if( rc!=0 ){
1390 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001391 return;
1392 }
drh6369bc32016-03-21 16:06:42 +00001393 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001394 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001395 return;
1396 }
1397 if( buf.st_nlink>1 ){
1398 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001399 return;
1400 }
drhb959a012013-12-07 12:29:22 +00001401 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001402 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001403 return;
1404 }
1405}
1406
1407
1408/*
danielk197713adf8a2004-06-03 16:08:41 +00001409** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001410** file by this or any other process. If such a lock is held, set *pResOut
1411** to a non-zero value otherwise *pResOut is set to zero. The return value
1412** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001413*/
danielk1977861f7452008-06-05 11:39:11 +00001414static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001415 int rc = SQLITE_OK;
1416 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001417 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001418
danielk1977861f7452008-06-05 11:39:11 +00001419 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1420
drh054889e2005-11-30 03:20:31 +00001421 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001422 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001423 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001424
1425 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001426 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001427 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001428 }
1429
drh2ac3ee92004-06-07 16:27:46 +00001430 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001431 */
danielk197709480a92009-02-09 05:32:32 +00001432#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001433 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001434 struct flock lock;
1435 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001436 lock.l_start = RESERVED_BYTE;
1437 lock.l_len = 1;
1438 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001439 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1440 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001441 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001442 } else if( lock.l_type!=F_UNLCK ){
1443 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001444 }
1445 }
danielk197709480a92009-02-09 05:32:32 +00001446#endif
danielk197713adf8a2004-06-03 16:08:41 +00001447
drh6c7d5c52008-11-21 20:32:33 +00001448 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001449 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001450
aswift5b1a2562008-08-22 00:22:35 +00001451 *pResOut = reserved;
1452 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001453}
1454
1455/*
drha7e61d82011-03-12 17:02:57 +00001456** Attempt to set a system-lock on the file pFile. The lock is
1457** described by pLock.
1458**
drh77197112011-03-15 19:08:48 +00001459** If the pFile was opened read/write from unix-excl, then the only lock
1460** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001461** the first time any lock is attempted. All subsequent system locking
1462** operations become no-ops. Locking operations still happen internally,
1463** in order to coordinate access between separate database connections
1464** within this process, but all of that is handled in memory and the
1465** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001466**
1467** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1468** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1469** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001470**
1471** Zero is returned if the call completes successfully, or -1 if a call
1472** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001473*/
1474static int unixFileLock(unixFile *pFile, struct flock *pLock){
1475 int rc;
drh3cb93392011-03-12 18:10:44 +00001476 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001477 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001478 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001479 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001480 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001481 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001482 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001483 lock.l_whence = SEEK_SET;
1484 lock.l_start = SHARED_FIRST;
1485 lock.l_len = SHARED_SIZE;
1486 lock.l_type = F_WRLCK;
1487 rc = osFcntl(pFile->h, F_SETLK, &lock);
1488 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001489 pInode->bProcessLock = 1;
1490 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001491 }else{
1492 rc = 0;
1493 }
1494 }else{
1495 rc = osFcntl(pFile->h, F_SETLK, pLock);
1496 }
1497 return rc;
1498}
1499
1500/*
drh308c2a52010-05-14 11:30:18 +00001501** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001502** of the following:
1503**
drh2ac3ee92004-06-07 16:27:46 +00001504** (1) SHARED_LOCK
1505** (2) RESERVED_LOCK
1506** (3) PENDING_LOCK
1507** (4) EXCLUSIVE_LOCK
1508**
drhb3e04342004-06-08 00:47:47 +00001509** Sometimes when requesting one lock state, additional lock states
1510** are inserted in between. The locking might fail on one of the later
1511** transitions leaving the lock state different from what it started but
1512** still short of its goal. The following chart shows the allowed
1513** transitions and the inserted intermediate states:
1514**
1515** UNLOCKED -> SHARED
1516** SHARED -> RESERVED
1517** SHARED -> (PENDING) -> EXCLUSIVE
1518** RESERVED -> (PENDING) -> EXCLUSIVE
1519** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001520**
drha6abd042004-06-09 17:37:22 +00001521** This routine will only increase a lock. Use the sqlite3OsUnlock()
1522** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001523*/
drh308c2a52010-05-14 11:30:18 +00001524static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001525 /* The following describes the implementation of the various locks and
1526 ** lock transitions in terms of the POSIX advisory shared and exclusive
1527 ** lock primitives (called read-locks and write-locks below, to avoid
1528 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001529 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001530 ** accessing the same database file, in case that is ever required.
1531 **
1532 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1533 ** byte', each single bytes at well known offsets, and the 'shared byte
1534 ** range', a range of 510 bytes at a well known offset.
1535 **
1536 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001537 ** byte'. If this is successful, 'shared byte range' is read-locked
1538 ** and the lock on the 'pending byte' released. (Legacy note: When
1539 ** SQLite was first developed, Windows95 systems were still very common,
1540 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1541 ** single randomly selected by from the 'shared byte range' is locked.
1542 ** Windows95 is now pretty much extinct, but this work-around for the
1543 ** lack of shared-locks on Windows95 lives on, for backwards
1544 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001545 **
danielk197790ba3bd2004-06-25 08:32:25 +00001546 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1547 ** A RESERVED lock is implemented by grabbing a write-lock on the
1548 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001549 **
1550 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001551 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1552 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1553 ** obtained, but existing SHARED locks are allowed to persist. A process
1554 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1555 ** This property is used by the algorithm for rolling back a journal file
1556 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001557 **
danielk197790ba3bd2004-06-25 08:32:25 +00001558 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1559 ** implemented by obtaining a write-lock on the entire 'shared byte
1560 ** range'. Since all other locks require a read-lock on one of the bytes
1561 ** within this range, this ensures that no other locks are held on the
1562 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001563 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001564 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001565 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001566 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001567 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001568 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001569
drh054889e2005-11-30 03:20:31 +00001570 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001571 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1572 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001573 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001574 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001575
1576 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001577 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001578 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001579 */
drh308c2a52010-05-14 11:30:18 +00001580 if( pFile->eFileLock>=eFileLock ){
1581 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1582 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001583 return SQLITE_OK;
1584 }
1585
drh0c2694b2009-09-03 16:23:44 +00001586 /* Make sure the locking sequence is correct.
1587 ** (1) We never move from unlocked to anything higher than shared lock.
1588 ** (2) SQLite never explicitly requests a pendig lock.
1589 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001590 */
drh308c2a52010-05-14 11:30:18 +00001591 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1592 assert( eFileLock!=PENDING_LOCK );
1593 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001594
drh8af6c222010-05-14 12:43:01 +00001595 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001596 */
drh6c7d5c52008-11-21 20:32:33 +00001597 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001598 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001599
danielk1977ad94b582007-08-20 06:44:22 +00001600 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001601 ** handle that precludes the requested lock, return BUSY.
1602 */
drh8af6c222010-05-14 12:43:01 +00001603 if( (pFile->eFileLock!=pInode->eFileLock &&
1604 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001605 ){
1606 rc = SQLITE_BUSY;
1607 goto end_lock;
1608 }
1609
1610 /* If a SHARED lock is requested, and some thread using this PID already
1611 ** has a SHARED or RESERVED lock, then increment reference counts and
1612 ** return SQLITE_OK.
1613 */
drh308c2a52010-05-14 11:30:18 +00001614 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001615 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001616 assert( eFileLock==SHARED_LOCK );
1617 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001618 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001619 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001620 pInode->nShared++;
1621 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001622 goto end_lock;
1623 }
1624
danielk19779a1d0ab2004-06-01 14:09:28 +00001625
drh3cde3bb2004-06-12 02:17:14 +00001626 /* A PENDING lock is needed before acquiring a SHARED lock and before
1627 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1628 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001629 */
drh0c2694b2009-09-03 16:23:44 +00001630 lock.l_len = 1L;
1631 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001632 if( eFileLock==SHARED_LOCK
1633 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001634 ){
drh308c2a52010-05-14 11:30:18 +00001635 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001636 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001637 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001638 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001639 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001640 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001641 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001642 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001643 goto end_lock;
1644 }
drh3cde3bb2004-06-12 02:17:14 +00001645 }
1646
1647
1648 /* If control gets to this point, then actually go ahead and make
1649 ** operating system calls for the specified lock.
1650 */
drh308c2a52010-05-14 11:30:18 +00001651 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001652 assert( pInode->nShared==0 );
1653 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001654 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001655
drh2ac3ee92004-06-07 16:27:46 +00001656 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001657 lock.l_start = SHARED_FIRST;
1658 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001659 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001660 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001661 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001662 }
dan661d71a2011-03-30 19:08:03 +00001663
drh2ac3ee92004-06-07 16:27:46 +00001664 /* Drop the temporary PENDING lock */
1665 lock.l_start = PENDING_BYTE;
1666 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001667 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001668 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1669 /* This could happen with a network mount */
1670 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001671 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001672 }
dan661d71a2011-03-30 19:08:03 +00001673
1674 if( rc ){
1675 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001676 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001677 }
dan661d71a2011-03-30 19:08:03 +00001678 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001679 }else{
drh308c2a52010-05-14 11:30:18 +00001680 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001681 pInode->nLock++;
1682 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001683 }
drh8af6c222010-05-14 12:43:01 +00001684 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001685 /* We are trying for an exclusive lock but another thread in this
1686 ** same process is still holding a shared lock. */
1687 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001688 }else{
drh3cde3bb2004-06-12 02:17:14 +00001689 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001690 ** assumed that there is a SHARED or greater lock on the file
1691 ** already.
1692 */
drh308c2a52010-05-14 11:30:18 +00001693 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001694 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001695
1696 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1697 if( eFileLock==RESERVED_LOCK ){
1698 lock.l_start = RESERVED_BYTE;
1699 lock.l_len = 1L;
1700 }else{
1701 lock.l_start = SHARED_FIRST;
1702 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001703 }
dan661d71a2011-03-30 19:08:03 +00001704
1705 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001706 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001707 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001708 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001709 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001710 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001711 }
drhbbd42a62004-05-22 17:41:58 +00001712 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001713
drh8f941bc2009-01-14 23:03:40 +00001714
drhd3d8c042012-05-29 17:02:40 +00001715#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001716 /* Set up the transaction-counter change checking flags when
1717 ** transitioning from a SHARED to a RESERVED lock. The change
1718 ** from SHARED to RESERVED marks the beginning of a normal
1719 ** write operation (not a hot journal rollback).
1720 */
1721 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001722 && pFile->eFileLock<=SHARED_LOCK
1723 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001724 ){
1725 pFile->transCntrChng = 0;
1726 pFile->dbUpdate = 0;
1727 pFile->inNormalWrite = 1;
1728 }
1729#endif
1730
1731
danielk1977ecb2a962004-06-02 06:30:16 +00001732 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001733 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001734 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001735 }else if( eFileLock==EXCLUSIVE_LOCK ){
1736 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001737 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001738 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001739
1740end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001741 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001742 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1743 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001744 return rc;
1745}
1746
1747/*
dan08da86a2009-08-21 17:18:03 +00001748** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001749** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001750*/
1751static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001752 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001753 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001754 p->pNext = pInode->pUnused;
1755 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001756 pFile->h = -1;
1757 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001758}
1759
1760/*
drh308c2a52010-05-14 11:30:18 +00001761** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001762** must be either NO_LOCK or SHARED_LOCK.
1763**
1764** If the locking level of the file descriptor is already at or below
1765** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001766**
1767** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1768** the byte range is divided into 2 parts and the first part is unlocked then
1769** set to a read lock, then the other part is simply unlocked. This works
1770** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1771** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001772*/
drha7e61d82011-03-12 17:02:57 +00001773static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001774 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001775 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001776 struct flock lock;
1777 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001778
drh054889e2005-11-30 03:20:31 +00001779 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001780 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001781 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001782 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001783
drh308c2a52010-05-14 11:30:18 +00001784 assert( eFileLock<=SHARED_LOCK );
1785 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001786 return SQLITE_OK;
1787 }
drh6c7d5c52008-11-21 20:32:33 +00001788 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001789 pInode = pFile->pInode;
1790 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001791 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001792 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001793
drhd3d8c042012-05-29 17:02:40 +00001794#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001795 /* When reducing a lock such that other processes can start
1796 ** reading the database file again, make sure that the
1797 ** transaction counter was updated if any part of the database
1798 ** file changed. If the transaction counter is not updated,
1799 ** other connections to the same file might not realize that
1800 ** the file has changed and hence might not know to flush their
1801 ** cache. The use of a stale cache can lead to database corruption.
1802 */
drh8f941bc2009-01-14 23:03:40 +00001803 pFile->inNormalWrite = 0;
1804#endif
1805
drh7ed97b92010-01-20 13:07:21 +00001806 /* downgrading to a shared lock on NFS involves clearing the write lock
1807 ** before establishing the readlock - to avoid a race condition we downgrade
1808 ** the lock in 2 blocks, so that part of the range will be covered by a
1809 ** write lock until the rest is covered by a read lock:
1810 ** 1: [WWWWW]
1811 ** 2: [....W]
1812 ** 3: [RRRRW]
1813 ** 4: [RRRR.]
1814 */
drh308c2a52010-05-14 11:30:18 +00001815 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001816#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001817 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001818 assert( handleNFSUnlock==0 );
1819#endif
1820#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001821 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001822 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001823 off_t divSize = SHARED_SIZE - 1;
1824
1825 lock.l_type = F_UNLCK;
1826 lock.l_whence = SEEK_SET;
1827 lock.l_start = SHARED_FIRST;
1828 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001829 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001830 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001831 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001832 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001833 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001834 }
drh7ed97b92010-01-20 13:07:21 +00001835 lock.l_type = F_RDLCK;
1836 lock.l_whence = SEEK_SET;
1837 lock.l_start = SHARED_FIRST;
1838 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001839 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001840 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001841 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1842 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001843 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001844 }
1845 goto end_unlock;
1846 }
1847 lock.l_type = F_UNLCK;
1848 lock.l_whence = SEEK_SET;
1849 lock.l_start = SHARED_FIRST+divSize;
1850 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001851 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001852 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001853 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001854 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001855 goto end_unlock;
1856 }
drh30f776f2011-02-25 03:25:07 +00001857 }else
1858#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1859 {
drh7ed97b92010-01-20 13:07:21 +00001860 lock.l_type = F_RDLCK;
1861 lock.l_whence = SEEK_SET;
1862 lock.l_start = SHARED_FIRST;
1863 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001864 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001865 /* In theory, the call to unixFileLock() cannot fail because another
1866 ** process is holding an incompatible lock. If it does, this
1867 ** indicates that the other process is not following the locking
1868 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1869 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1870 ** an assert to fail). */
1871 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001872 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001873 goto end_unlock;
1874 }
drh9c105bb2004-10-02 20:38:28 +00001875 }
1876 }
drhbbd42a62004-05-22 17:41:58 +00001877 lock.l_type = F_UNLCK;
1878 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001879 lock.l_start = PENDING_BYTE;
1880 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001881 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001882 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001883 }else{
danea83bc62011-04-01 11:56:32 +00001884 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001885 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001886 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001887 }
drhbbd42a62004-05-22 17:41:58 +00001888 }
drh308c2a52010-05-14 11:30:18 +00001889 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001890 /* Decrement the shared lock counter. Release the lock using an
1891 ** OS call only when all threads in this same process have released
1892 ** the lock.
1893 */
drh8af6c222010-05-14 12:43:01 +00001894 pInode->nShared--;
1895 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001896 lock.l_type = F_UNLCK;
1897 lock.l_whence = SEEK_SET;
1898 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001899 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001900 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001901 }else{
danea83bc62011-04-01 11:56:32 +00001902 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001903 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001904 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001905 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001906 }
drha6abd042004-06-09 17:37:22 +00001907 }
1908
drhbbd42a62004-05-22 17:41:58 +00001909 /* Decrement the count of locks against this same file. When the
1910 ** count reaches zero, close any other file descriptors whose close
1911 ** was deferred because of outstanding locks.
1912 */
drh8af6c222010-05-14 12:43:01 +00001913 pInode->nLock--;
1914 assert( pInode->nLock>=0 );
1915 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001916 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001917 }
1918 }
drhf2f105d2012-08-20 15:53:54 +00001919
aswift5b1a2562008-08-22 00:22:35 +00001920end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001921 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001922 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001923 return rc;
drhbbd42a62004-05-22 17:41:58 +00001924}
1925
1926/*
drh308c2a52010-05-14 11:30:18 +00001927** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001928** must be either NO_LOCK or SHARED_LOCK.
1929**
1930** If the locking level of the file descriptor is already at or below
1931** the requested locking level, this routine is a no-op.
1932*/
drh308c2a52010-05-14 11:30:18 +00001933static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001934#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001935 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001936#endif
drha7e61d82011-03-12 17:02:57 +00001937 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001938}
1939
mistachkine98844f2013-08-24 00:59:24 +00001940#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001941static int unixMapfile(unixFile *pFd, i64 nByte);
1942static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001943#endif
danf23da962013-03-23 21:00:41 +00001944
drh7ed97b92010-01-20 13:07:21 +00001945/*
danielk1977e339d652008-06-28 11:23:00 +00001946** This function performs the parts of the "close file" operation
1947** common to all locking schemes. It closes the directory and file
1948** handles, if they are valid, and sets all fields of the unixFile
1949** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001950**
1951** It is *not* necessary to hold the mutex when this routine is called,
1952** even on VxWorks. A mutex will be acquired on VxWorks by the
1953** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001954*/
1955static int closeUnixFile(sqlite3_file *id){
1956 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001957#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001958 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001959#endif
dan661d71a2011-03-30 19:08:03 +00001960 if( pFile->h>=0 ){
1961 robust_close(pFile, pFile->h, __LINE__);
1962 pFile->h = -1;
1963 }
1964#if OS_VXWORKS
1965 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001966 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001967 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001968 }
1969 vxworksReleaseFileId(pFile->pId);
1970 pFile->pId = 0;
1971 }
1972#endif
drh0bdbc902014-06-16 18:35:06 +00001973#ifdef SQLITE_UNLINK_AFTER_CLOSE
1974 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1975 osUnlink(pFile->zPath);
1976 sqlite3_free(*(char**)&pFile->zPath);
1977 pFile->zPath = 0;
1978 }
1979#endif
dan661d71a2011-03-30 19:08:03 +00001980 OSTRACE(("CLOSE %-3d\n", pFile->h));
1981 OpenCounter(-1);
1982 sqlite3_free(pFile->pUnused);
1983 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001984 return SQLITE_OK;
1985}
1986
1987/*
danielk1977e3026632004-06-22 11:29:02 +00001988** Close a file.
1989*/
danielk197762079062007-08-15 17:08:46 +00001990static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001991 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001992 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001993 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001994 unixUnlock(id, NO_LOCK);
1995 unixEnterMutex();
1996
1997 /* unixFile.pInode is always valid here. Otherwise, a different close
1998 ** routine (e.g. nolockClose()) would be called instead.
1999 */
2000 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
2001 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
2002 /* If there are outstanding locks, do not actually close the file just
2003 ** yet because that would clear those locks. Instead, add the file
2004 ** descriptor to pInode->pUnused list. It will be automatically closed
2005 ** when the last lock is cleared.
2006 */
2007 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002008 }
dan661d71a2011-03-30 19:08:03 +00002009 releaseInodeInfo(pFile);
2010 rc = closeUnixFile(id);
2011 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002012 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002013}
2014
drh734c9862008-11-28 15:37:20 +00002015/************** End of the posix advisory lock implementation *****************
2016******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002017
drh734c9862008-11-28 15:37:20 +00002018/******************************************************************************
2019****************************** No-op Locking **********************************
2020**
2021** Of the various locking implementations available, this is by far the
2022** simplest: locking is ignored. No attempt is made to lock the database
2023** file for reading or writing.
2024**
2025** This locking mode is appropriate for use on read-only databases
2026** (ex: databases that are burned into CD-ROM, for example.) It can
2027** also be used if the application employs some external mechanism to
2028** prevent simultaneous access of the same database by two or more
2029** database connections. But there is a serious risk of database
2030** corruption if this locking mode is used in situations where multiple
2031** database connections are accessing the same database file at the same
2032** time and one or more of those connections are writing.
2033*/
drhbfe66312006-10-03 17:40:40 +00002034
drh734c9862008-11-28 15:37:20 +00002035static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2036 UNUSED_PARAMETER(NotUsed);
2037 *pResOut = 0;
2038 return SQLITE_OK;
2039}
drh734c9862008-11-28 15:37:20 +00002040static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2041 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2042 return SQLITE_OK;
2043}
drh734c9862008-11-28 15:37:20 +00002044static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2045 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2046 return SQLITE_OK;
2047}
2048
2049/*
drh9b35ea62008-11-29 02:20:26 +00002050** Close the file.
drh734c9862008-11-28 15:37:20 +00002051*/
2052static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002053 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002054}
2055
2056/******************* End of the no-op lock implementation *********************
2057******************************************************************************/
2058
2059/******************************************************************************
2060************************* Begin dot-file Locking ******************************
2061**
mistachkin48864df2013-03-21 21:20:32 +00002062** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002063** files (really a directory) to control access to the database. This works
2064** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002065**
2066** (1) There is zero concurrency. A single reader blocks all other
2067** connections from reading or writing the database.
2068**
2069** (2) An application crash or power loss can leave stale lock files
2070** sitting around that need to be cleared manually.
2071**
2072** Nevertheless, a dotlock is an appropriate locking mode for use if no
2073** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002074**
drh9ef6bc42011-11-04 02:24:02 +00002075** Dotfile locking works by creating a subdirectory in the same directory as
2076** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002077** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002078** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002079*/
2080
2081/*
2082** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002083** lock directory.
drh734c9862008-11-28 15:37:20 +00002084*/
2085#define DOTLOCK_SUFFIX ".lock"
2086
drh7708e972008-11-29 00:56:52 +00002087/*
2088** This routine checks if there is a RESERVED lock held on the specified
2089** file by this or any other process. If such a lock is held, set *pResOut
2090** to a non-zero value otherwise *pResOut is set to zero. The return value
2091** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2092**
2093** In dotfile locking, either a lock exists or it does not. So in this
2094** variation of CheckReservedLock(), *pResOut is set to true if any lock
2095** is held on the file and false if the file is unlocked.
2096*/
drh734c9862008-11-28 15:37:20 +00002097static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2098 int rc = SQLITE_OK;
2099 int reserved = 0;
2100 unixFile *pFile = (unixFile*)id;
2101
2102 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2103
2104 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002105 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002106 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002107 *pResOut = reserved;
2108 return rc;
2109}
2110
drh7708e972008-11-29 00:56:52 +00002111/*
drh308c2a52010-05-14 11:30:18 +00002112** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002113** of the following:
2114**
2115** (1) SHARED_LOCK
2116** (2) RESERVED_LOCK
2117** (3) PENDING_LOCK
2118** (4) EXCLUSIVE_LOCK
2119**
2120** Sometimes when requesting one lock state, additional lock states
2121** are inserted in between. The locking might fail on one of the later
2122** transitions leaving the lock state different from what it started but
2123** still short of its goal. The following chart shows the allowed
2124** transitions and the inserted intermediate states:
2125**
2126** UNLOCKED -> SHARED
2127** SHARED -> RESERVED
2128** SHARED -> (PENDING) -> EXCLUSIVE
2129** RESERVED -> (PENDING) -> EXCLUSIVE
2130** PENDING -> EXCLUSIVE
2131**
2132** This routine will only increase a lock. Use the sqlite3OsUnlock()
2133** routine to lower a locking level.
2134**
2135** With dotfile locking, we really only support state (4): EXCLUSIVE.
2136** But we track the other locking levels internally.
2137*/
drh308c2a52010-05-14 11:30:18 +00002138static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002139 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002140 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002141 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002142
drh7708e972008-11-29 00:56:52 +00002143
2144 /* If we have any lock, then the lock file already exists. All we have
2145 ** to do is adjust our internal record of the lock level.
2146 */
drh308c2a52010-05-14 11:30:18 +00002147 if( pFile->eFileLock > NO_LOCK ){
2148 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002149 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002150#ifdef HAVE_UTIME
2151 utime(zLockFile, NULL);
2152#else
drh734c9862008-11-28 15:37:20 +00002153 utimes(zLockFile, NULL);
2154#endif
drh7708e972008-11-29 00:56:52 +00002155 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002156 }
2157
2158 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002159 rc = osMkdir(zLockFile, 0777);
2160 if( rc<0 ){
2161 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002162 int tErrno = errno;
2163 if( EEXIST == tErrno ){
2164 rc = SQLITE_BUSY;
2165 } else {
2166 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002167 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002168 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002169 }
2170 }
drh7708e972008-11-29 00:56:52 +00002171 return rc;
drh734c9862008-11-28 15:37:20 +00002172 }
drh734c9862008-11-28 15:37:20 +00002173
2174 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002175 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002176 return rc;
2177}
2178
drh7708e972008-11-29 00:56:52 +00002179/*
drh308c2a52010-05-14 11:30:18 +00002180** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002181** must be either NO_LOCK or SHARED_LOCK.
2182**
2183** If the locking level of the file descriptor is already at or below
2184** the requested locking level, this routine is a no-op.
2185**
2186** When the locking level reaches NO_LOCK, delete the lock file.
2187*/
drh308c2a52010-05-14 11:30:18 +00002188static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002189 unixFile *pFile = (unixFile*)id;
2190 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002191 int rc;
drh734c9862008-11-28 15:37:20 +00002192
2193 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002194 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002195 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002196 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002197
2198 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002199 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002200 return SQLITE_OK;
2201 }
drh7708e972008-11-29 00:56:52 +00002202
2203 /* To downgrade to shared, simply update our internal notion of the
2204 ** lock state. No need to mess with the file on disk.
2205 */
drh308c2a52010-05-14 11:30:18 +00002206 if( eFileLock==SHARED_LOCK ){
2207 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002208 return SQLITE_OK;
2209 }
2210
drh7708e972008-11-29 00:56:52 +00002211 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002212 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002213 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002214 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002215 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002216 if( tErrno==ENOENT ){
2217 rc = SQLITE_OK;
2218 }else{
danea83bc62011-04-01 11:56:32 +00002219 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002220 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002221 }
2222 return rc;
2223 }
drh308c2a52010-05-14 11:30:18 +00002224 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002225 return SQLITE_OK;
2226}
2227
2228/*
drh9b35ea62008-11-29 02:20:26 +00002229** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002230*/
2231static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002232 unixFile *pFile = (unixFile*)id;
2233 assert( id!=0 );
2234 dotlockUnlock(id, NO_LOCK);
2235 sqlite3_free(pFile->lockingContext);
2236 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002237}
2238/****************** End of the dot-file lock implementation *******************
2239******************************************************************************/
2240
2241/******************************************************************************
2242************************** Begin flock Locking ********************************
2243**
2244** Use the flock() system call to do file locking.
2245**
drh6b9d6dd2008-12-03 19:34:47 +00002246** flock() locking is like dot-file locking in that the various
2247** fine-grain locking levels supported by SQLite are collapsed into
2248** a single exclusive lock. In other words, SHARED, RESERVED, and
2249** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2250** still works when you do this, but concurrency is reduced since
2251** only a single process can be reading the database at a time.
2252**
drhe89b2912015-03-03 20:42:01 +00002253** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002254*/
drhe89b2912015-03-03 20:42:01 +00002255#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002256
drh6b9d6dd2008-12-03 19:34:47 +00002257/*
drhff812312011-02-23 13:33:46 +00002258** Retry flock() calls that fail with EINTR
2259*/
2260#ifdef EINTR
2261static int robust_flock(int fd, int op){
2262 int rc;
2263 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2264 return rc;
2265}
2266#else
drh5c819272011-02-23 14:00:12 +00002267# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002268#endif
2269
2270
2271/*
drh6b9d6dd2008-12-03 19:34:47 +00002272** This routine checks if there is a RESERVED lock held on the specified
2273** file by this or any other process. If such a lock is held, set *pResOut
2274** to a non-zero value otherwise *pResOut is set to zero. The return value
2275** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2276*/
drh734c9862008-11-28 15:37:20 +00002277static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2278 int rc = SQLITE_OK;
2279 int reserved = 0;
2280 unixFile *pFile = (unixFile*)id;
2281
2282 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2283
2284 assert( pFile );
2285
2286 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002287 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002288 reserved = 1;
2289 }
2290
2291 /* Otherwise see if some other process holds it. */
2292 if( !reserved ){
2293 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002294 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002295 if( !lrc ){
2296 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002297 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002298 if ( lrc ) {
2299 int tErrno = errno;
2300 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002301 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002302 storeLastErrno(pFile, tErrno);
2303 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002304 }
2305 } else {
2306 int tErrno = errno;
2307 reserved = 1;
2308 /* someone else might have it reserved */
2309 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2310 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002311 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002312 rc = lrc;
2313 }
2314 }
2315 }
drh308c2a52010-05-14 11:30:18 +00002316 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002317
2318#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2319 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2320 rc = SQLITE_OK;
2321 reserved=1;
2322 }
2323#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2324 *pResOut = reserved;
2325 return rc;
2326}
2327
drh6b9d6dd2008-12-03 19:34:47 +00002328/*
drh308c2a52010-05-14 11:30:18 +00002329** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002330** of the following:
2331**
2332** (1) SHARED_LOCK
2333** (2) RESERVED_LOCK
2334** (3) PENDING_LOCK
2335** (4) EXCLUSIVE_LOCK
2336**
2337** Sometimes when requesting one lock state, additional lock states
2338** are inserted in between. The locking might fail on one of the later
2339** transitions leaving the lock state different from what it started but
2340** still short of its goal. The following chart shows the allowed
2341** transitions and the inserted intermediate states:
2342**
2343** UNLOCKED -> SHARED
2344** SHARED -> RESERVED
2345** SHARED -> (PENDING) -> EXCLUSIVE
2346** RESERVED -> (PENDING) -> EXCLUSIVE
2347** PENDING -> EXCLUSIVE
2348**
2349** flock() only really support EXCLUSIVE locks. We track intermediate
2350** lock states in the sqlite3_file structure, but all locks SHARED or
2351** above are really EXCLUSIVE locks and exclude all other processes from
2352** access the file.
2353**
2354** This routine will only increase a lock. Use the sqlite3OsUnlock()
2355** routine to lower a locking level.
2356*/
drh308c2a52010-05-14 11:30:18 +00002357static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002358 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002359 unixFile *pFile = (unixFile*)id;
2360
2361 assert( pFile );
2362
2363 /* if we already have a lock, it is exclusive.
2364 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002365 if (pFile->eFileLock > NO_LOCK) {
2366 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002367 return SQLITE_OK;
2368 }
2369
2370 /* grab an exclusive lock */
2371
drhff812312011-02-23 13:33:46 +00002372 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002373 int tErrno = errno;
2374 /* didn't get, must be busy */
2375 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2376 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002377 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002378 }
2379 } else {
2380 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002381 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002382 }
drh308c2a52010-05-14 11:30:18 +00002383 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2384 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002385#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2386 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2387 rc = SQLITE_BUSY;
2388 }
2389#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2390 return rc;
2391}
2392
drh6b9d6dd2008-12-03 19:34:47 +00002393
2394/*
drh308c2a52010-05-14 11:30:18 +00002395** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002396** must be either NO_LOCK or SHARED_LOCK.
2397**
2398** If the locking level of the file descriptor is already at or below
2399** the requested locking level, this routine is a no-op.
2400*/
drh308c2a52010-05-14 11:30:18 +00002401static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002402 unixFile *pFile = (unixFile*)id;
2403
2404 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002405 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002406 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002407 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002408
2409 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002410 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002411 return SQLITE_OK;
2412 }
2413
2414 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002415 if (eFileLock==SHARED_LOCK) {
2416 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002417 return SQLITE_OK;
2418 }
2419
2420 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002421 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002422#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002423 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002424#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002425 return SQLITE_IOERR_UNLOCK;
2426 }else{
drh308c2a52010-05-14 11:30:18 +00002427 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002428 return SQLITE_OK;
2429 }
2430}
2431
2432/*
2433** Close a file.
2434*/
2435static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002436 assert( id!=0 );
2437 flockUnlock(id, NO_LOCK);
2438 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002439}
2440
2441#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2442
2443/******************* End of the flock lock implementation *********************
2444******************************************************************************/
2445
2446/******************************************************************************
2447************************ Begin Named Semaphore Locking ************************
2448**
2449** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002450**
2451** Semaphore locking is like dot-lock and flock in that it really only
2452** supports EXCLUSIVE locking. Only a single process can read or write
2453** the database file at a time. This reduces potential concurrency, but
2454** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002455*/
2456#if OS_VXWORKS
2457
drh6b9d6dd2008-12-03 19:34:47 +00002458/*
2459** This routine checks if there is a RESERVED lock held on the specified
2460** file by this or any other process. If such a lock is held, set *pResOut
2461** to a non-zero value otherwise *pResOut is set to zero. The return value
2462** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2463*/
drh8cd5b252015-03-02 22:06:43 +00002464static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002465 int rc = SQLITE_OK;
2466 int reserved = 0;
2467 unixFile *pFile = (unixFile*)id;
2468
2469 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2470
2471 assert( pFile );
2472
2473 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002474 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002475 reserved = 1;
2476 }
2477
2478 /* Otherwise see if some other process holds it. */
2479 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002480 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002481
2482 if( sem_trywait(pSem)==-1 ){
2483 int tErrno = errno;
2484 if( EAGAIN != tErrno ){
2485 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002486 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002487 } else {
2488 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002489 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002490 }
2491 }else{
2492 /* we could have it if we want it */
2493 sem_post(pSem);
2494 }
2495 }
drh308c2a52010-05-14 11:30:18 +00002496 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002497
2498 *pResOut = reserved;
2499 return rc;
2500}
2501
drh6b9d6dd2008-12-03 19:34:47 +00002502/*
drh308c2a52010-05-14 11:30:18 +00002503** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002504** of the following:
2505**
2506** (1) SHARED_LOCK
2507** (2) RESERVED_LOCK
2508** (3) PENDING_LOCK
2509** (4) EXCLUSIVE_LOCK
2510**
2511** Sometimes when requesting one lock state, additional lock states
2512** are inserted in between. The locking might fail on one of the later
2513** transitions leaving the lock state different from what it started but
2514** still short of its goal. The following chart shows the allowed
2515** transitions and the inserted intermediate states:
2516**
2517** UNLOCKED -> SHARED
2518** SHARED -> RESERVED
2519** SHARED -> (PENDING) -> EXCLUSIVE
2520** RESERVED -> (PENDING) -> EXCLUSIVE
2521** PENDING -> EXCLUSIVE
2522**
2523** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2524** lock states in the sqlite3_file structure, but all locks SHARED or
2525** above are really EXCLUSIVE locks and exclude all other processes from
2526** access the file.
2527**
2528** This routine will only increase a lock. Use the sqlite3OsUnlock()
2529** routine to lower a locking level.
2530*/
drh8cd5b252015-03-02 22:06:43 +00002531static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002532 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002533 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002534 int rc = SQLITE_OK;
2535
2536 /* if we already have a lock, it is exclusive.
2537 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002538 if (pFile->eFileLock > NO_LOCK) {
2539 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002540 rc = SQLITE_OK;
2541 goto sem_end_lock;
2542 }
2543
2544 /* lock semaphore now but bail out when already locked. */
2545 if( sem_trywait(pSem)==-1 ){
2546 rc = SQLITE_BUSY;
2547 goto sem_end_lock;
2548 }
2549
2550 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002551 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002552
2553 sem_end_lock:
2554 return rc;
2555}
2556
drh6b9d6dd2008-12-03 19:34:47 +00002557/*
drh308c2a52010-05-14 11:30:18 +00002558** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002559** must be either NO_LOCK or SHARED_LOCK.
2560**
2561** If the locking level of the file descriptor is already at or below
2562** the requested locking level, this routine is a no-op.
2563*/
drh8cd5b252015-03-02 22:06:43 +00002564static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002565 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002566 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002567
2568 assert( pFile );
2569 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002570 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002571 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002572 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002573
2574 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002575 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002576 return SQLITE_OK;
2577 }
2578
2579 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002580 if (eFileLock==SHARED_LOCK) {
2581 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002582 return SQLITE_OK;
2583 }
2584
2585 /* no, really unlock. */
2586 if ( sem_post(pSem)==-1 ) {
2587 int rc, tErrno = errno;
2588 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2589 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002590 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002591 }
2592 return rc;
2593 }
drh308c2a52010-05-14 11:30:18 +00002594 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002595 return SQLITE_OK;
2596}
2597
2598/*
2599 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002600 */
drh8cd5b252015-03-02 22:06:43 +00002601static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002602 if( id ){
2603 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002604 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002605 assert( pFile );
2606 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002607 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002608 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002609 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002610 }
2611 return SQLITE_OK;
2612}
2613
2614#endif /* OS_VXWORKS */
2615/*
2616** Named semaphore locking is only available on VxWorks.
2617**
2618*************** End of the named semaphore lock implementation ****************
2619******************************************************************************/
2620
2621
2622/******************************************************************************
2623*************************** Begin AFP Locking *********************************
2624**
2625** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2626** on Apple Macintosh computers - both OS9 and OSX.
2627**
2628** Third-party implementations of AFP are available. But this code here
2629** only works on OSX.
2630*/
2631
drhd2cb50b2009-01-09 21:41:17 +00002632#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002633/*
2634** The afpLockingContext structure contains all afp lock specific state
2635*/
drhbfe66312006-10-03 17:40:40 +00002636typedef struct afpLockingContext afpLockingContext;
2637struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002638 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002639 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002640};
2641
2642struct ByteRangeLockPB2
2643{
2644 unsigned long long offset; /* offset to first byte to lock */
2645 unsigned long long length; /* nbr of bytes to lock */
2646 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2647 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2648 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2649 int fd; /* file desc to assoc this lock with */
2650};
2651
drhfd131da2007-08-07 17:13:03 +00002652#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002653
drh6b9d6dd2008-12-03 19:34:47 +00002654/*
2655** This is a utility for setting or clearing a bit-range lock on an
2656** AFP filesystem.
2657**
2658** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2659*/
2660static int afpSetLock(
2661 const char *path, /* Name of the file to be locked or unlocked */
2662 unixFile *pFile, /* Open file descriptor on path */
2663 unsigned long long offset, /* First byte to be locked */
2664 unsigned long long length, /* Number of bytes to lock */
2665 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002666){
drh6b9d6dd2008-12-03 19:34:47 +00002667 struct ByteRangeLockPB2 pb;
2668 int err;
drhbfe66312006-10-03 17:40:40 +00002669
2670 pb.unLockFlag = setLockFlag ? 0 : 1;
2671 pb.startEndFlag = 0;
2672 pb.offset = offset;
2673 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002674 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002675
drh308c2a52010-05-14 11:30:18 +00002676 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002677 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002678 offset, length));
drhbfe66312006-10-03 17:40:40 +00002679 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2680 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002681 int rc;
2682 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002683 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2684 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002685#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2686 rc = SQLITE_BUSY;
2687#else
drh734c9862008-11-28 15:37:20 +00002688 rc = sqliteErrorFromPosixError(tErrno,
2689 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002690#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002691 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002692 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002693 }
2694 return rc;
drhbfe66312006-10-03 17:40:40 +00002695 } else {
aswift5b1a2562008-08-22 00:22:35 +00002696 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002697 }
2698}
2699
drh6b9d6dd2008-12-03 19:34:47 +00002700/*
2701** This routine checks if there is a RESERVED lock held on the specified
2702** file by this or any other process. If such a lock is held, set *pResOut
2703** to a non-zero value otherwise *pResOut is set to zero. The return value
2704** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2705*/
danielk1977e339d652008-06-28 11:23:00 +00002706static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002707 int rc = SQLITE_OK;
2708 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002709 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002710 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002711
aswift5b1a2562008-08-22 00:22:35 +00002712 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2713
2714 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002715 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002716 if( context->reserved ){
2717 *pResOut = 1;
2718 return SQLITE_OK;
2719 }
drh8af6c222010-05-14 12:43:01 +00002720 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002721
2722 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002723 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002724 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002725 }
2726
2727 /* Otherwise see if some other process holds it.
2728 */
aswift5b1a2562008-08-22 00:22:35 +00002729 if( !reserved ){
2730 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002731 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002732 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002733 /* if we succeeded in taking the reserved lock, unlock it to restore
2734 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002735 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002736 } else {
2737 /* if we failed to get the lock then someone else must have it */
2738 reserved = 1;
2739 }
2740 if( IS_LOCK_ERROR(lrc) ){
2741 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002742 }
2743 }
drhbfe66312006-10-03 17:40:40 +00002744
drh7ed97b92010-01-20 13:07:21 +00002745 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002746 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002747
2748 *pResOut = reserved;
2749 return rc;
drhbfe66312006-10-03 17:40:40 +00002750}
2751
drh6b9d6dd2008-12-03 19:34:47 +00002752/*
drh308c2a52010-05-14 11:30:18 +00002753** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002754** of the following:
2755**
2756** (1) SHARED_LOCK
2757** (2) RESERVED_LOCK
2758** (3) PENDING_LOCK
2759** (4) EXCLUSIVE_LOCK
2760**
2761** Sometimes when requesting one lock state, additional lock states
2762** are inserted in between. The locking might fail on one of the later
2763** transitions leaving the lock state different from what it started but
2764** still short of its goal. The following chart shows the allowed
2765** transitions and the inserted intermediate states:
2766**
2767** UNLOCKED -> SHARED
2768** SHARED -> RESERVED
2769** SHARED -> (PENDING) -> EXCLUSIVE
2770** RESERVED -> (PENDING) -> EXCLUSIVE
2771** PENDING -> EXCLUSIVE
2772**
2773** This routine will only increase a lock. Use the sqlite3OsUnlock()
2774** routine to lower a locking level.
2775*/
drh308c2a52010-05-14 11:30:18 +00002776static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002777 int rc = SQLITE_OK;
2778 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002779 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002780 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002781
2782 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002783 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2784 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002785 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002786
drhbfe66312006-10-03 17:40:40 +00002787 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002788 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002789 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002790 */
drh308c2a52010-05-14 11:30:18 +00002791 if( pFile->eFileLock>=eFileLock ){
2792 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2793 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002794 return SQLITE_OK;
2795 }
2796
2797 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002798 ** (1) We never move from unlocked to anything higher than shared lock.
2799 ** (2) SQLite never explicitly requests a pendig lock.
2800 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002801 */
drh308c2a52010-05-14 11:30:18 +00002802 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2803 assert( eFileLock!=PENDING_LOCK );
2804 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002805
drh8af6c222010-05-14 12:43:01 +00002806 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002807 */
drh6c7d5c52008-11-21 20:32:33 +00002808 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002809 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002810
2811 /* If some thread using this PID has a lock via a different unixFile*
2812 ** handle that precludes the requested lock, return BUSY.
2813 */
drh8af6c222010-05-14 12:43:01 +00002814 if( (pFile->eFileLock!=pInode->eFileLock &&
2815 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002816 ){
2817 rc = SQLITE_BUSY;
2818 goto afp_end_lock;
2819 }
2820
2821 /* If a SHARED lock is requested, and some thread using this PID already
2822 ** has a SHARED or RESERVED lock, then increment reference counts and
2823 ** return SQLITE_OK.
2824 */
drh308c2a52010-05-14 11:30:18 +00002825 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002826 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002827 assert( eFileLock==SHARED_LOCK );
2828 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002829 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002830 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002831 pInode->nShared++;
2832 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002833 goto afp_end_lock;
2834 }
drhbfe66312006-10-03 17:40:40 +00002835
2836 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002837 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2838 ** be released.
2839 */
drh308c2a52010-05-14 11:30:18 +00002840 if( eFileLock==SHARED_LOCK
2841 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002842 ){
2843 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002844 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002845 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002846 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002847 goto afp_end_lock;
2848 }
2849 }
2850
2851 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002852 ** operating system calls for the specified lock.
2853 */
drh308c2a52010-05-14 11:30:18 +00002854 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002855 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002856 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002857
drh8af6c222010-05-14 12:43:01 +00002858 assert( pInode->nShared==0 );
2859 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002860
2861 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002862 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002863 /* note that the quality of the randomness doesn't matter that much */
2864 lk = random();
drh8af6c222010-05-14 12:43:01 +00002865 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002866 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002867 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002868 if( IS_LOCK_ERROR(lrc1) ){
2869 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002870 }
aswift5b1a2562008-08-22 00:22:35 +00002871 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002872 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002873
aswift5b1a2562008-08-22 00:22:35 +00002874 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002875 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002876 rc = lrc1;
2877 goto afp_end_lock;
2878 } else if( IS_LOCK_ERROR(lrc2) ){
2879 rc = lrc2;
2880 goto afp_end_lock;
2881 } else if( lrc1 != SQLITE_OK ) {
2882 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002883 } else {
drh308c2a52010-05-14 11:30:18 +00002884 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002885 pInode->nLock++;
2886 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002887 }
drh8af6c222010-05-14 12:43:01 +00002888 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002889 /* We are trying for an exclusive lock but another thread in this
2890 ** same process is still holding a shared lock. */
2891 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002892 }else{
2893 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2894 ** assumed that there is a SHARED or greater lock on the file
2895 ** already.
2896 */
2897 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002898 assert( 0!=pFile->eFileLock );
2899 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002900 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002901 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002902 if( !failed ){
2903 context->reserved = 1;
2904 }
drhbfe66312006-10-03 17:40:40 +00002905 }
drh308c2a52010-05-14 11:30:18 +00002906 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002907 /* Acquire an EXCLUSIVE lock */
2908
2909 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002910 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002911 */
drh6b9d6dd2008-12-03 19:34:47 +00002912 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002913 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002914 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002915 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002916 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002917 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002918 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002919 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002920 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2921 ** a critical I/O error
2922 */
2923 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2924 SQLITE_IOERR_LOCK;
2925 goto afp_end_lock;
2926 }
2927 }else{
aswift5b1a2562008-08-22 00:22:35 +00002928 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002929 }
2930 }
aswift5b1a2562008-08-22 00:22:35 +00002931 if( failed ){
2932 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002933 }
2934 }
2935
2936 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002937 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002938 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002939 }else if( eFileLock==EXCLUSIVE_LOCK ){
2940 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002941 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002942 }
2943
2944afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002945 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002946 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2947 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002948 return rc;
2949}
2950
2951/*
drh308c2a52010-05-14 11:30:18 +00002952** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002953** must be either NO_LOCK or SHARED_LOCK.
2954**
2955** If the locking level of the file descriptor is already at or below
2956** the requested locking level, this routine is a no-op.
2957*/
drh308c2a52010-05-14 11:30:18 +00002958static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002959 int rc = SQLITE_OK;
2960 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002961 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002962 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2963 int skipShared = 0;
2964#ifdef SQLITE_TEST
2965 int h = pFile->h;
2966#endif
drhbfe66312006-10-03 17:40:40 +00002967
2968 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002969 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002970 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002971 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002972
drh308c2a52010-05-14 11:30:18 +00002973 assert( eFileLock<=SHARED_LOCK );
2974 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002975 return SQLITE_OK;
2976 }
drh6c7d5c52008-11-21 20:32:33 +00002977 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002978 pInode = pFile->pInode;
2979 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002980 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002981 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002982 SimulateIOErrorBenign(1);
2983 SimulateIOError( h=(-1) )
2984 SimulateIOErrorBenign(0);
2985
drhd3d8c042012-05-29 17:02:40 +00002986#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002987 /* When reducing a lock such that other processes can start
2988 ** reading the database file again, make sure that the
2989 ** transaction counter was updated if any part of the database
2990 ** file changed. If the transaction counter is not updated,
2991 ** other connections to the same file might not realize that
2992 ** the file has changed and hence might not know to flush their
2993 ** cache. The use of a stale cache can lead to database corruption.
2994 */
2995 assert( pFile->inNormalWrite==0
2996 || pFile->dbUpdate==0
2997 || pFile->transCntrChng==1 );
2998 pFile->inNormalWrite = 0;
2999#endif
aswiftaebf4132008-11-21 00:10:35 +00003000
drh308c2a52010-05-14 11:30:18 +00003001 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003002 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003003 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003004 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003005 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003006 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3007 } else {
3008 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003009 }
3010 }
drh308c2a52010-05-14 11:30:18 +00003011 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003012 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003013 }
drh308c2a52010-05-14 11:30:18 +00003014 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003015 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3016 if( !rc ){
3017 context->reserved = 0;
3018 }
aswiftaebf4132008-11-21 00:10:35 +00003019 }
drh8af6c222010-05-14 12:43:01 +00003020 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3021 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003022 }
aswiftaebf4132008-11-21 00:10:35 +00003023 }
drh308c2a52010-05-14 11:30:18 +00003024 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003025
drh7ed97b92010-01-20 13:07:21 +00003026 /* Decrement the shared lock counter. Release the lock using an
3027 ** OS call only when all threads in this same process have released
3028 ** the lock.
3029 */
drh8af6c222010-05-14 12:43:01 +00003030 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3031 pInode->nShared--;
3032 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003033 SimulateIOErrorBenign(1);
3034 SimulateIOError( h=(-1) )
3035 SimulateIOErrorBenign(0);
3036 if( !skipShared ){
3037 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3038 }
3039 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003040 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003041 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003042 }
3043 }
3044 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003045 pInode->nLock--;
3046 assert( pInode->nLock>=0 );
3047 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003048 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003049 }
3050 }
drhbfe66312006-10-03 17:40:40 +00003051 }
drh7ed97b92010-01-20 13:07:21 +00003052
drh6c7d5c52008-11-21 20:32:33 +00003053 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003054 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003055 return rc;
3056}
3057
3058/*
drh339eb0b2008-03-07 15:34:11 +00003059** Close a file & cleanup AFP specific locking context
3060*/
danielk1977e339d652008-06-28 11:23:00 +00003061static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003062 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003063 unixFile *pFile = (unixFile*)id;
3064 assert( id!=0 );
3065 afpUnlock(id, NO_LOCK);
3066 unixEnterMutex();
3067 if( pFile->pInode && pFile->pInode->nLock ){
3068 /* If there are outstanding locks, do not actually close the file just
3069 ** yet because that would clear those locks. Instead, add the file
3070 ** descriptor to pInode->aPending. It will be automatically closed when
3071 ** the last lock is cleared.
3072 */
3073 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003074 }
drha8de1e12015-11-30 00:05:39 +00003075 releaseInodeInfo(pFile);
3076 sqlite3_free(pFile->lockingContext);
3077 rc = closeUnixFile(id);
3078 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003079 return rc;
drhbfe66312006-10-03 17:40:40 +00003080}
3081
drhd2cb50b2009-01-09 21:41:17 +00003082#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003083/*
3084** The code above is the AFP lock implementation. The code is specific
3085** to MacOSX and does not work on other unix platforms. No alternative
3086** is available. If you don't compile for a mac, then the "unix-afp"
3087** VFS is not available.
3088**
3089********************* End of the AFP lock implementation **********************
3090******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003091
drh7ed97b92010-01-20 13:07:21 +00003092/******************************************************************************
3093*************************** Begin NFS Locking ********************************/
3094
3095#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3096/*
drh308c2a52010-05-14 11:30:18 +00003097 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003098 ** must be either NO_LOCK or SHARED_LOCK.
3099 **
3100 ** If the locking level of the file descriptor is already at or below
3101 ** the requested locking level, this routine is a no-op.
3102 */
drh308c2a52010-05-14 11:30:18 +00003103static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003104 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003105}
3106
3107#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3108/*
3109** The code above is the NFS lock implementation. The code is specific
3110** to MacOSX and does not work on other unix platforms. No alternative
3111** is available.
3112**
3113********************* End of the NFS lock implementation **********************
3114******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003115
3116/******************************************************************************
3117**************** Non-locking sqlite3_file methods *****************************
3118**
3119** The next division contains implementations for all methods of the
3120** sqlite3_file object other than the locking methods. The locking
3121** methods were defined in divisions above (one locking method per
3122** division). Those methods that are common to all locking modes
3123** are gather together into this division.
3124*/
drhbfe66312006-10-03 17:40:40 +00003125
3126/*
drh734c9862008-11-28 15:37:20 +00003127** Seek to the offset passed as the second argument, then read cnt
3128** bytes into pBuf. Return the number of bytes actually read.
3129**
3130** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3131** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3132** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003133** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003134** See tickets #2741 and #2681.
3135**
3136** To avoid stomping the errno value on a failed read the lastErrno value
3137** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003138*/
drh734c9862008-11-28 15:37:20 +00003139static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3140 int got;
drh58024642011-11-07 18:16:00 +00003141 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003142#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3143 i64 newOffset;
3144#endif
drh734c9862008-11-28 15:37:20 +00003145 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003146 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003147 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003148 do{
drh734c9862008-11-28 15:37:20 +00003149#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003150 got = osPread(id->h, pBuf, cnt, offset);
3151 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003152#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003153 got = osPread64(id->h, pBuf, cnt, offset);
3154 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003155#else
drha46cadc2016-03-04 03:02:06 +00003156 newOffset = lseek(id->h, offset, SEEK_SET);
3157 SimulateIOError( newOffset = -1 );
3158 if( newOffset<0 ){
3159 storeLastErrno((unixFile*)id, errno);
3160 return -1;
3161 }
3162 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003163#endif
drh58024642011-11-07 18:16:00 +00003164 if( got==cnt ) break;
3165 if( got<0 ){
3166 if( errno==EINTR ){ got = 1; continue; }
3167 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003168 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003169 break;
3170 }else if( got>0 ){
3171 cnt -= got;
3172 offset += got;
3173 prior += got;
3174 pBuf = (void*)(got + (char*)pBuf);
3175 }
3176 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003177 TIMER_END;
drh58024642011-11-07 18:16:00 +00003178 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3179 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3180 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003181}
3182
3183/*
drh734c9862008-11-28 15:37:20 +00003184** Read data from a file into a buffer. Return SQLITE_OK if all
3185** bytes were read successfully and SQLITE_IOERR if anything goes
3186** wrong.
drh339eb0b2008-03-07 15:34:11 +00003187*/
drh734c9862008-11-28 15:37:20 +00003188static int unixRead(
3189 sqlite3_file *id,
3190 void *pBuf,
3191 int amt,
3192 sqlite3_int64 offset
3193){
dan08da86a2009-08-21 17:18:03 +00003194 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003195 int got;
3196 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003197 assert( offset>=0 );
3198 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003199
dan08da86a2009-08-21 17:18:03 +00003200 /* If this is a database file (not a journal, master-journal or temp
3201 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003202#if 0
dane946c392009-08-22 11:39:46 +00003203 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003204 || offset>=PENDING_BYTE+512
3205 || offset+amt<=PENDING_BYTE
3206 );
dan7c246102010-04-12 19:00:29 +00003207#endif
drh08c6d442009-02-09 17:34:07 +00003208
drh9b4c59f2013-04-15 17:03:42 +00003209#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003210 /* Deal with as much of this read request as possible by transfering
3211 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003212 if( offset<pFile->mmapSize ){
3213 if( offset+amt <= pFile->mmapSize ){
3214 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3215 return SQLITE_OK;
3216 }else{
3217 int nCopy = pFile->mmapSize - offset;
3218 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3219 pBuf = &((u8 *)pBuf)[nCopy];
3220 amt -= nCopy;
3221 offset += nCopy;
3222 }
3223 }
drh6e0b6d52013-04-09 16:19:20 +00003224#endif
danf23da962013-03-23 21:00:41 +00003225
dan08da86a2009-08-21 17:18:03 +00003226 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003227 if( got==amt ){
3228 return SQLITE_OK;
3229 }else if( got<0 ){
3230 /* lastErrno set by seekAndRead */
3231 return SQLITE_IOERR_READ;
3232 }else{
drh4bf66fd2015-02-19 02:43:02 +00003233 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003234 /* Unread parts of the buffer must be zero-filled */
3235 memset(&((char*)pBuf)[got], 0, amt-got);
3236 return SQLITE_IOERR_SHORT_READ;
3237 }
3238}
3239
3240/*
dan47a2b4a2013-04-26 16:09:29 +00003241** Attempt to seek the file-descriptor passed as the first argument to
3242** absolute offset iOff, then attempt to write nBuf bytes of data from
3243** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3244** return the actual number of bytes written (which may be less than
3245** nBuf).
3246*/
3247static int seekAndWriteFd(
3248 int fd, /* File descriptor to write to */
3249 i64 iOff, /* File offset to begin writing at */
3250 const void *pBuf, /* Copy data from this buffer to the file */
3251 int nBuf, /* Size of buffer pBuf in bytes */
3252 int *piErrno /* OUT: Error number if error occurs */
3253){
3254 int rc = 0; /* Value returned by system call */
3255
3256 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003257 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003258 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003259 nBuf &= 0x1ffff;
3260 TIMER_START;
3261
3262#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003263 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003264#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003265 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003266#else
3267 do{
3268 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003269 SimulateIOError( iSeek = -1 );
3270 if( iSeek<0 ){
3271 rc = -1;
3272 break;
dan47a2b4a2013-04-26 16:09:29 +00003273 }
3274 rc = osWrite(fd, pBuf, nBuf);
3275 }while( rc<0 && errno==EINTR );
3276#endif
3277
3278 TIMER_END;
3279 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3280
drhe1818ec2015-12-01 16:21:35 +00003281 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003282 return rc;
3283}
3284
3285
3286/*
drh734c9862008-11-28 15:37:20 +00003287** Seek to the offset in id->offset then read cnt bytes into pBuf.
3288** Return the number of bytes actually read. Update the offset.
3289**
3290** To avoid stomping the errno value on a failed write the lastErrno value
3291** is set before returning.
3292*/
3293static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003294 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003295}
3296
3297
3298/*
3299** Write data from a buffer into a file. Return SQLITE_OK on success
3300** or some other error code on failure.
3301*/
3302static int unixWrite(
3303 sqlite3_file *id,
3304 const void *pBuf,
3305 int amt,
3306 sqlite3_int64 offset
3307){
dan08da86a2009-08-21 17:18:03 +00003308 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003309 int wrote = 0;
3310 assert( id );
3311 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003312
dan08da86a2009-08-21 17:18:03 +00003313 /* If this is a database file (not a journal, master-journal or temp
3314 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003315#if 0
dane946c392009-08-22 11:39:46 +00003316 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003317 || offset>=PENDING_BYTE+512
3318 || offset+amt<=PENDING_BYTE
3319 );
dan7c246102010-04-12 19:00:29 +00003320#endif
drh08c6d442009-02-09 17:34:07 +00003321
drhd3d8c042012-05-29 17:02:40 +00003322#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003323 /* If we are doing a normal write to a database file (as opposed to
3324 ** doing a hot-journal rollback or a write to some file other than a
3325 ** normal database file) then record the fact that the database
3326 ** has changed. If the transaction counter is modified, record that
3327 ** fact too.
3328 */
dan08da86a2009-08-21 17:18:03 +00003329 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003330 pFile->dbUpdate = 1; /* The database has been modified */
3331 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003332 int rc;
drh8f941bc2009-01-14 23:03:40 +00003333 char oldCntr[4];
3334 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003335 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003336 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003337 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003338 pFile->transCntrChng = 1; /* The transaction counter has changed */
3339 }
3340 }
3341 }
3342#endif
3343
danfe33e392015-11-17 20:56:06 +00003344#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003345 /* Deal with as much of this write request as possible by transfering
3346 ** data from the memory mapping using memcpy(). */
3347 if( offset<pFile->mmapSize ){
3348 if( offset+amt <= pFile->mmapSize ){
3349 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3350 return SQLITE_OK;
3351 }else{
3352 int nCopy = pFile->mmapSize - offset;
3353 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3354 pBuf = &((u8 *)pBuf)[nCopy];
3355 amt -= nCopy;
3356 offset += nCopy;
3357 }
3358 }
drh6e0b6d52013-04-09 16:19:20 +00003359#endif
drh02bf8b42015-09-01 23:51:53 +00003360
3361 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003362 amt -= wrote;
3363 offset += wrote;
3364 pBuf = &((char*)pBuf)[wrote];
3365 }
3366 SimulateIOError(( wrote=(-1), amt=1 ));
3367 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003368
drh02bf8b42015-09-01 23:51:53 +00003369 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003370 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003371 /* lastErrno set by seekAndWrite */
3372 return SQLITE_IOERR_WRITE;
3373 }else{
drh4bf66fd2015-02-19 02:43:02 +00003374 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003375 return SQLITE_FULL;
3376 }
3377 }
dan6e09d692010-07-27 18:34:15 +00003378
drh734c9862008-11-28 15:37:20 +00003379 return SQLITE_OK;
3380}
3381
3382#ifdef SQLITE_TEST
3383/*
3384** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003385** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003386*/
3387int sqlite3_sync_count = 0;
3388int sqlite3_fullsync_count = 0;
3389#endif
3390
3391/*
drh89240432009-03-25 01:06:01 +00003392** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003393** Others do no. To be safe, we will stick with the (slightly slower)
3394** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003395** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003396*/
drhf7a4a1b2015-01-10 18:02:45 +00003397#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003398# define fdatasync fsync
3399#endif
3400
3401/*
3402** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3403** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3404** only available on Mac OS X. But that could change.
3405*/
3406#ifdef F_FULLFSYNC
3407# define HAVE_FULLFSYNC 1
3408#else
3409# define HAVE_FULLFSYNC 0
3410#endif
3411
3412
3413/*
3414** The fsync() system call does not work as advertised on many
3415** unix systems. The following procedure is an attempt to make
3416** it work better.
3417**
3418** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3419** for testing when we want to run through the test suite quickly.
3420** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3421** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3422** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003423**
3424** SQLite sets the dataOnly flag if the size of the file is unchanged.
3425** The idea behind dataOnly is that it should only write the file content
3426** to disk, not the inode. We only set dataOnly if the file size is
3427** unchanged since the file size is part of the inode. However,
3428** Ted Ts'o tells us that fdatasync() will also write the inode if the
3429** file size has changed. The only real difference between fdatasync()
3430** and fsync(), Ted tells us, is that fdatasync() will not flush the
3431** inode if the mtime or owner or other inode attributes have changed.
3432** We only care about the file size, not the other file attributes, so
3433** as far as SQLite is concerned, an fdatasync() is always adequate.
3434** So, we always use fdatasync() if it is available, regardless of
3435** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003436*/
3437static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003438 int rc;
drh734c9862008-11-28 15:37:20 +00003439
3440 /* The following "ifdef/elif/else/" block has the same structure as
3441 ** the one below. It is replicated here solely to avoid cluttering
3442 ** up the real code with the UNUSED_PARAMETER() macros.
3443 */
3444#ifdef SQLITE_NO_SYNC
3445 UNUSED_PARAMETER(fd);
3446 UNUSED_PARAMETER(fullSync);
3447 UNUSED_PARAMETER(dataOnly);
3448#elif HAVE_FULLFSYNC
3449 UNUSED_PARAMETER(dataOnly);
3450#else
3451 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003452 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003453#endif
3454
3455 /* Record the number of times that we do a normal fsync() and
3456 ** FULLSYNC. This is used during testing to verify that this procedure
3457 ** gets called with the correct arguments.
3458 */
3459#ifdef SQLITE_TEST
3460 if( fullSync ) sqlite3_fullsync_count++;
3461 sqlite3_sync_count++;
3462#endif
3463
3464 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003465 ** no-op. But go ahead and call fstat() to validate the file
3466 ** descriptor as we need a method to provoke a failure during
3467 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003468 */
3469#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003470 {
3471 struct stat buf;
3472 rc = osFstat(fd, &buf);
3473 }
drh734c9862008-11-28 15:37:20 +00003474#elif HAVE_FULLFSYNC
3475 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003476 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003477 }else{
3478 rc = 1;
3479 }
3480 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003481 ** It shouldn't be possible for fullfsync to fail on the local
3482 ** file system (on OSX), so failure indicates that FULLFSYNC
3483 ** isn't supported for this file system. So, attempt an fsync
3484 ** and (for now) ignore the overhead of a superfluous fcntl call.
3485 ** It'd be better to detect fullfsync support once and avoid
3486 ** the fcntl call every time sync is called.
3487 */
drh734c9862008-11-28 15:37:20 +00003488 if( rc ) rc = fsync(fd);
3489
drh7ed97b92010-01-20 13:07:21 +00003490#elif defined(__APPLE__)
3491 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3492 ** so currently we default to the macro that redefines fdatasync to fsync
3493 */
3494 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003495#else
drh0b647ff2009-03-21 14:41:04 +00003496 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003497#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003498 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003499 rc = fsync(fd);
3500 }
drh0b647ff2009-03-21 14:41:04 +00003501#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003502#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3503
3504 if( OS_VXWORKS && rc!= -1 ){
3505 rc = 0;
3506 }
chw97185482008-11-17 08:05:31 +00003507 return rc;
drhbfe66312006-10-03 17:40:40 +00003508}
3509
drh734c9862008-11-28 15:37:20 +00003510/*
drh0059eae2011-08-08 23:48:40 +00003511** Open a file descriptor to the directory containing file zFilename.
3512** If successful, *pFd is set to the opened file descriptor and
3513** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3514** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3515** value.
3516**
drh90315a22011-08-10 01:52:12 +00003517** The directory file descriptor is used for only one thing - to
3518** fsync() a directory to make sure file creation and deletion events
3519** are flushed to disk. Such fsyncs are not needed on newer
3520** journaling filesystems, but are required on older filesystems.
3521**
3522** This routine can be overridden using the xSetSysCall interface.
3523** The ability to override this routine was added in support of the
3524** chromium sandbox. Opening a directory is a security risk (we are
3525** told) so making it overrideable allows the chromium sandbox to
3526** replace this routine with a harmless no-op. To make this routine
3527** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3528** *pFd set to a negative number.
3529**
drh0059eae2011-08-08 23:48:40 +00003530** If SQLITE_OK is returned, the caller is responsible for closing
3531** the file descriptor *pFd using close().
3532*/
3533static int openDirectory(const char *zFilename, int *pFd){
3534 int ii;
3535 int fd = -1;
3536 char zDirname[MAX_PATHNAME+1];
3537
3538 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003539 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3540 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003541 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003542 }else{
3543 if( zDirname[0]!='/' ) zDirname[0] = '.';
3544 zDirname[1] = 0;
3545 }
3546 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3547 if( fd>=0 ){
3548 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003549 }
3550 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003551 if( fd>=0 ) return SQLITE_OK;
3552 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003553}
3554
3555/*
drh734c9862008-11-28 15:37:20 +00003556** Make sure all writes to a particular file are committed to disk.
3557**
3558** If dataOnly==0 then both the file itself and its metadata (file
3559** size, access time, etc) are synced. If dataOnly!=0 then only the
3560** file data is synced.
3561**
3562** Under Unix, also make sure that the directory entry for the file
3563** has been created by fsync-ing the directory that contains the file.
3564** If we do not do this and we encounter a power failure, the directory
3565** entry for the journal might not exist after we reboot. The next
3566** SQLite to access the file will not know that the journal exists (because
3567** the directory entry for the journal was never created) and the transaction
3568** will not roll back - possibly leading to database corruption.
3569*/
3570static int unixSync(sqlite3_file *id, int flags){
3571 int rc;
3572 unixFile *pFile = (unixFile*)id;
3573
3574 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3575 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3576
3577 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3578 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3579 || (flags&0x0F)==SQLITE_SYNC_FULL
3580 );
3581
3582 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3583 ** line is to test that doing so does not cause any problems.
3584 */
3585 SimulateDiskfullError( return SQLITE_FULL );
3586
3587 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003588 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003589 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3590 SimulateIOError( rc=1 );
3591 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003592 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003593 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003594 }
drh0059eae2011-08-08 23:48:40 +00003595
3596 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003597 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003598 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003599 */
3600 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3601 int dirfd;
3602 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003603 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003604 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003605 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003606 full_fsync(dirfd, 0, 0);
3607 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003608 }else{
3609 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003610 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003611 }
drh0059eae2011-08-08 23:48:40 +00003612 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003613 }
3614 return rc;
3615}
3616
3617/*
3618** Truncate an open file to a specified size
3619*/
3620static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003621 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003622 int rc;
dan6e09d692010-07-27 18:34:15 +00003623 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003624 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003625
3626 /* If the user has configured a chunk-size for this file, truncate the
3627 ** file so that it consists of an integer number of chunks (i.e. the
3628 ** actual file size after the operation may be larger than the requested
3629 ** size).
3630 */
drhb8af4b72012-04-05 20:04:39 +00003631 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003632 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3633 }
3634
dan2ee53412014-09-06 16:49:40 +00003635 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003636 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003637 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003638 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003639 }else{
drhd3d8c042012-05-29 17:02:40 +00003640#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003641 /* If we are doing a normal write to a database file (as opposed to
3642 ** doing a hot-journal rollback or a write to some file other than a
3643 ** normal database file) and we truncate the file to zero length,
3644 ** that effectively updates the change counter. This might happen
3645 ** when restoring a database using the backup API from a zero-length
3646 ** source.
3647 */
dan6e09d692010-07-27 18:34:15 +00003648 if( pFile->inNormalWrite && nByte==0 ){
3649 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003650 }
danf23da962013-03-23 21:00:41 +00003651#endif
danc0003312013-03-22 17:46:11 +00003652
mistachkine98844f2013-08-24 00:59:24 +00003653#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003654 /* If the file was just truncated to a size smaller than the currently
3655 ** mapped region, reduce the effective mapping size as well. SQLite will
3656 ** use read() and write() to access data beyond this point from now on.
3657 */
3658 if( nByte<pFile->mmapSize ){
3659 pFile->mmapSize = nByte;
3660 }
mistachkine98844f2013-08-24 00:59:24 +00003661#endif
drh3313b142009-11-06 04:13:18 +00003662
drh734c9862008-11-28 15:37:20 +00003663 return SQLITE_OK;
3664 }
3665}
3666
3667/*
3668** Determine the current size of a file in bytes
3669*/
3670static int unixFileSize(sqlite3_file *id, i64 *pSize){
3671 int rc;
3672 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003673 assert( id );
3674 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003675 SimulateIOError( rc=1 );
3676 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003677 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003678 return SQLITE_IOERR_FSTAT;
3679 }
3680 *pSize = buf.st_size;
3681
drh8af6c222010-05-14 12:43:01 +00003682 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003683 ** writes a single byte into that file in order to work around a bug
3684 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3685 ** layers, we need to report this file size as zero even though it is
3686 ** really 1. Ticket #3260.
3687 */
3688 if( *pSize==1 ) *pSize = 0;
3689
3690
3691 return SQLITE_OK;
3692}
3693
drhd2cb50b2009-01-09 21:41:17 +00003694#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003695/*
3696** Handler for proxy-locking file-control verbs. Defined below in the
3697** proxying locking division.
3698*/
3699static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003700#endif
drh715ff302008-12-03 22:32:44 +00003701
dan502019c2010-07-28 14:26:17 +00003702/*
3703** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003704** file-control operation. Enlarge the database to nBytes in size
3705** (rounded up to the next chunk-size). If the database is already
3706** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003707*/
3708static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003709 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003710 i64 nSize; /* Required file size */
3711 struct stat buf; /* Used to hold return values of fstat() */
3712
drh4bf66fd2015-02-19 02:43:02 +00003713 if( osFstat(pFile->h, &buf) ){
3714 return SQLITE_IOERR_FSTAT;
3715 }
dan502019c2010-07-28 14:26:17 +00003716
3717 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3718 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003719
dan502019c2010-07-28 14:26:17 +00003720#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003721 /* The code below is handling the return value of osFallocate()
3722 ** correctly. posix_fallocate() is defined to "returns zero on success,
3723 ** or an error number on failure". See the manpage for details. */
3724 int err;
drhff812312011-02-23 13:33:46 +00003725 do{
dan661d71a2011-03-30 19:08:03 +00003726 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3727 }while( err==EINTR );
3728 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003729#else
dan592bf7f2014-12-30 19:58:31 +00003730 /* If the OS does not have posix_fallocate(), fake it. Write a
3731 ** single byte to the last byte in each block that falls entirely
3732 ** within the extended region. Then, if required, a single byte
3733 ** at offset (nSize-1), to set the size of the file correctly.
3734 ** This is a similar technique to that used by glibc on systems
3735 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003736 */
3737 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003738 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003739 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003740
drh053378d2015-12-01 22:09:42 +00003741 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003742 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003743 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003744 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3745 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003746 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003747 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003748 }
dan502019c2010-07-28 14:26:17 +00003749#endif
3750 }
3751 }
3752
mistachkine98844f2013-08-24 00:59:24 +00003753#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003754 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003755 int rc;
3756 if( pFile->szChunk<=0 ){
3757 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003758 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003759 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3760 }
3761 }
3762
3763 rc = unixMapfile(pFile, nByte);
3764 return rc;
3765 }
mistachkine98844f2013-08-24 00:59:24 +00003766#endif
danf23da962013-03-23 21:00:41 +00003767
dan502019c2010-07-28 14:26:17 +00003768 return SQLITE_OK;
3769}
danielk1977ad94b582007-08-20 06:44:22 +00003770
danielk1977e3026632004-06-22 11:29:02 +00003771/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003772** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003773** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3774**
3775** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3776*/
3777static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3778 if( *pArg<0 ){
3779 *pArg = (pFile->ctrlFlags & mask)!=0;
3780 }else if( (*pArg)==0 ){
3781 pFile->ctrlFlags &= ~mask;
3782 }else{
3783 pFile->ctrlFlags |= mask;
3784 }
3785}
3786
drh696b33e2012-12-06 19:01:42 +00003787/* Forward declaration */
3788static int unixGetTempname(int nBuf, char *zBuf);
3789
drhf12b3f62011-12-21 14:42:29 +00003790/*
drh9e33c2c2007-08-31 18:34:59 +00003791** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003792*/
drhcc6bb3e2007-08-31 16:11:35 +00003793static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003794 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003795 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003796#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003797 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3798 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003799 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003800 }
3801 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3802 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003803 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003804 }
3805 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3806 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003807 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003808 }
drhd76dba72017-07-22 16:00:34 +00003809#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003810
drh9e33c2c2007-08-31 18:34:59 +00003811 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003812 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003813 return SQLITE_OK;
3814 }
drh4bf66fd2015-02-19 02:43:02 +00003815 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003816 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003817 return SQLITE_OK;
3818 }
dan6e09d692010-07-27 18:34:15 +00003819 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003820 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003821 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003822 }
drh9ff27ec2010-05-19 19:26:05 +00003823 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003824 int rc;
3825 SimulateIOErrorBenign(1);
3826 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3827 SimulateIOErrorBenign(0);
3828 return rc;
drhf0b190d2011-07-26 16:03:07 +00003829 }
3830 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003831 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3832 return SQLITE_OK;
3833 }
drhcb15f352011-12-23 01:04:17 +00003834 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3835 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003836 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003837 }
drhde60fc22011-12-14 17:53:36 +00003838 case SQLITE_FCNTL_VFSNAME: {
3839 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3840 return SQLITE_OK;
3841 }
drh696b33e2012-12-06 19:01:42 +00003842 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003843 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003844 if( zTFile ){
3845 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3846 *(char**)pArg = zTFile;
3847 }
3848 return SQLITE_OK;
3849 }
drhb959a012013-12-07 12:29:22 +00003850 case SQLITE_FCNTL_HAS_MOVED: {
3851 *(int*)pArg = fileHasMoved(pFile);
3852 return SQLITE_OK;
3853 }
mistachkine98844f2013-08-24 00:59:24 +00003854#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003855 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003856 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003857 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003858 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3859 newLimit = sqlite3GlobalConfig.mxMmap;
3860 }
dan43c1e622017-08-07 18:13:28 +00003861
3862 /* The value of newLimit may be eventually cast to (size_t) and passed
3863 ** to mmap(). Restrict its value to 2GB if (size_t) is a 32-bit type. */
3864 if( sizeof(size_t)<8 ){
3865 newLimit = (newLimit & 0x7FFFFFFF);
3866 }
3867
drh9b4c59f2013-04-15 17:03:42 +00003868 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003869 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003870 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003871 if( pFile->mmapSize>0 ){
3872 unixUnmapfile(pFile);
3873 rc = unixMapfile(pFile, -1);
3874 }
danbcb8a862013-04-08 15:30:41 +00003875 }
drh34e258c2013-05-23 01:40:53 +00003876 return rc;
danb2d3de32013-03-14 18:34:37 +00003877 }
mistachkine98844f2013-08-24 00:59:24 +00003878#endif
drhd3d8c042012-05-29 17:02:40 +00003879#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003880 /* The pager calls this method to signal that it has done
3881 ** a rollback and that the database is therefore unchanged and
3882 ** it hence it is OK for the transaction change counter to be
3883 ** unchanged.
3884 */
3885 case SQLITE_FCNTL_DB_UNCHANGED: {
3886 ((unixFile*)id)->dbUpdate = 0;
3887 return SQLITE_OK;
3888 }
3889#endif
drhd2cb50b2009-01-09 21:41:17 +00003890#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003891 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3892 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003893 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003894 }
drhd2cb50b2009-01-09 21:41:17 +00003895#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003896 }
drh0b52b7d2011-01-26 19:46:22 +00003897 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003898}
3899
3900/*
danefe16972017-07-20 19:49:14 +00003901** If pFd->sectorSize is non-zero when this function is called, it is a
3902** no-op. Otherwise, the values of pFd->sectorSize and
3903** pFd->deviceCharacteristics are set according to the file-system
3904** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00003905**
danefe16972017-07-20 19:49:14 +00003906** There are two versions of this function. One for QNX and one for all
3907** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00003908*/
danefe16972017-07-20 19:49:14 +00003909#ifndef __QNXNTO__
3910static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00003911 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00003912 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00003913#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003914 int res;
dan9d709542017-07-21 21:06:24 +00003915 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00003916
danefe16972017-07-20 19:49:14 +00003917 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00003918 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
3919 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00003920 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00003921 }
drhd76dba72017-07-22 16:00:34 +00003922#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003923
3924 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3925 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3926 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3927 }
3928
3929 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3930 }
3931}
3932#else
drh537dddf2012-10-26 13:46:24 +00003933#include <sys/dcmd_blk.h>
3934#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00003935static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00003936 if( pFile->sectorSize == 0 ){
3937 struct statvfs fsInfo;
3938
3939 /* Set defaults for non-supported filesystems */
3940 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3941 pFile->deviceCharacteristics = 0;
3942 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3943 return pFile->sectorSize;
3944 }
3945
3946 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3947 pFile->sectorSize = fsInfo.f_bsize;
3948 pFile->deviceCharacteristics =
3949 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3950 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3951 ** the write succeeds */
3952 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3953 ** so it is ordered */
3954 0;
3955 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3956 pFile->sectorSize = fsInfo.f_bsize;
3957 pFile->deviceCharacteristics =
3958 /* etfs cluster size writes are atomic */
3959 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3960 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3961 ** the write succeeds */
3962 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3963 ** so it is ordered */
3964 0;
3965 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3966 pFile->sectorSize = fsInfo.f_bsize;
3967 pFile->deviceCharacteristics =
3968 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3969 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3970 ** the write succeeds */
3971 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3972 ** so it is ordered */
3973 0;
3974 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3975 pFile->sectorSize = fsInfo.f_bsize;
3976 pFile->deviceCharacteristics =
3977 /* full bitset of atomics from max sector size and smaller */
3978 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3979 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3980 ** so it is ordered */
3981 0;
3982 }else if( strstr(fsInfo.f_basetype, "dos") ){
3983 pFile->sectorSize = fsInfo.f_bsize;
3984 pFile->deviceCharacteristics =
3985 /* full bitset of atomics from max sector size and smaller */
3986 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3987 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3988 ** so it is ordered */
3989 0;
3990 }else{
3991 pFile->deviceCharacteristics =
3992 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3993 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3994 ** the write succeeds */
3995 0;
3996 }
3997 }
3998 /* Last chance verification. If the sector size isn't a multiple of 512
3999 ** then it isn't valid.*/
4000 if( pFile->sectorSize % 512 != 0 ){
4001 pFile->deviceCharacteristics = 0;
4002 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4003 }
drh537dddf2012-10-26 13:46:24 +00004004}
danefe16972017-07-20 19:49:14 +00004005#endif
4006
4007/*
4008** Return the sector size in bytes of the underlying block device for
4009** the specified file. This is almost always 512 bytes, but may be
4010** larger for some devices.
4011**
4012** SQLite code assumes this function cannot fail. It also assumes that
4013** if two files are created in the same file-system directory (i.e.
4014** a database and its journal file) that the sector size will be the
4015** same for both.
4016*/
4017static int unixSectorSize(sqlite3_file *id){
4018 unixFile *pFd = (unixFile*)id;
4019 setDeviceCharacteristics(pFd);
4020 return pFd->sectorSize;
4021}
danielk1977a3d4c882007-03-23 10:08:38 +00004022
danielk197790949c22007-08-17 16:50:38 +00004023/*
drhf12b3f62011-12-21 14:42:29 +00004024** Return the device characteristics for the file.
4025**
drhcb15f352011-12-23 01:04:17 +00004026** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004027** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004028** file system does not always provide powersafe overwrites. (In other
4029** words, after a power-loss event, parts of the file that were never
4030** written might end up being altered.) However, non-PSOW behavior is very,
4031** very rare. And asserting PSOW makes a large reduction in the amount
4032** of required I/O for journaling, since a lot of padding is eliminated.
4033** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4034** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004035*/
drhf12b3f62011-12-21 14:42:29 +00004036static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004037 unixFile *pFd = (unixFile*)id;
4038 setDeviceCharacteristics(pFd);
4039 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004040}
4041
dan702eec12014-06-23 10:04:58 +00004042#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004043
dan702eec12014-06-23 10:04:58 +00004044/*
4045** Return the system page size.
4046**
4047** This function should not be called directly by other code in this file.
4048** Instead, it should be called via macro osGetpagesize().
4049*/
4050static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004051#if OS_VXWORKS
4052 return 1024;
4053#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004054 return getpagesize();
4055#else
4056 return (int)sysconf(_SC_PAGESIZE);
4057#endif
4058}
4059
4060#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4061
4062#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004063
4064/*
drhd91c68f2010-05-14 14:52:25 +00004065** Object used to represent an shared memory buffer.
4066**
4067** When multiple threads all reference the same wal-index, each thread
4068** has its own unixShm object, but they all point to a single instance
4069** of this unixShmNode object. In other words, each wal-index is opened
4070** only once per process.
4071**
4072** Each unixShmNode object is connected to a single unixInodeInfo object.
4073** We could coalesce this object into unixInodeInfo, but that would mean
4074** every open file that does not use shared memory (in other words, most
4075** open files) would have to carry around this extra information. So
4076** the unixInodeInfo object contains a pointer to this unixShmNode object
4077** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004078**
4079** unixMutexHeld() must be true when creating or destroying
4080** this object or while reading or writing the following fields:
4081**
4082** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004083**
4084** The following fields are read-only after the object is created:
4085**
4086** fid
4087** zFilename
4088**
drhd91c68f2010-05-14 14:52:25 +00004089** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004090** unixMutexHeld() is true when reading or writing any other field
4091** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004092*/
drhd91c68f2010-05-14 14:52:25 +00004093struct unixShmNode {
4094 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004095 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004096 char *zFilename; /* Name of the mmapped file */
4097 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004098 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004099 u16 nRegion; /* Size of array apRegion */
4100 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004101 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004102 int nRef; /* Number of unixShm objects pointing to this */
4103 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004104#ifdef SQLITE_DEBUG
4105 u8 exclMask; /* Mask of exclusive locks held */
4106 u8 sharedMask; /* Mask of shared locks held */
4107 u8 nextShmId; /* Next available unixShm.id value */
4108#endif
4109};
4110
4111/*
drhd9e5c4f2010-05-12 18:01:39 +00004112** Structure used internally by this VFS to record the state of an
4113** open shared memory connection.
4114**
drhd91c68f2010-05-14 14:52:25 +00004115** The following fields are initialized when this object is created and
4116** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004117**
drhd91c68f2010-05-14 14:52:25 +00004118** unixShm.pFile
4119** unixShm.id
4120**
4121** All other fields are read/write. The unixShm.pFile->mutex must be held
4122** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004123*/
4124struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004125 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4126 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004127 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004128 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004129 u16 sharedMask; /* Mask of shared locks held */
4130 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004131};
4132
4133/*
drhd9e5c4f2010-05-12 18:01:39 +00004134** Constants used for locking
4135*/
drhbd9676c2010-06-23 17:58:38 +00004136#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004137#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004138
drhd9e5c4f2010-05-12 18:01:39 +00004139/*
drh73b64e42010-05-30 19:55:15 +00004140** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004141**
4142** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4143** otherwise.
4144*/
4145static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004146 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004147 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004148 int ofst, /* First byte of the locking range */
4149 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004150){
drhbbf76ee2015-03-10 20:22:35 +00004151 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4152 struct flock f; /* The posix advisory locking structure */
4153 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004154
drhd91c68f2010-05-14 14:52:25 +00004155 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004156 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004157 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004158
drh73b64e42010-05-30 19:55:15 +00004159 /* Shared locks never span more than one byte */
4160 assert( n==1 || lockType!=F_RDLCK );
4161
4162 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004163 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004164
drh3cb93392011-03-12 18:10:44 +00004165 if( pShmNode->h>=0 ){
4166 /* Initialize the locking parameters */
4167 memset(&f, 0, sizeof(f));
4168 f.l_type = lockType;
4169 f.l_whence = SEEK_SET;
4170 f.l_start = ofst;
4171 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004172
drhdcfb9652015-12-02 00:05:26 +00004173 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004174 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4175 }
drhd9e5c4f2010-05-12 18:01:39 +00004176
4177 /* Update the global lock state and do debug tracing */
4178#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004179 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004180 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004181 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004182 if( rc==SQLITE_OK ){
4183 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004184 OSTRACE(("unlock %d ok", ofst));
4185 pShmNode->exclMask &= ~mask;
4186 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004187 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004188 OSTRACE(("read-lock %d ok", ofst));
4189 pShmNode->exclMask &= ~mask;
4190 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004191 }else{
4192 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004193 OSTRACE(("write-lock %d ok", ofst));
4194 pShmNode->exclMask |= mask;
4195 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004196 }
4197 }else{
4198 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004199 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004200 }else if( lockType==F_RDLCK ){
4201 OSTRACE(("read-lock failed"));
4202 }else{
4203 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004204 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004205 }
4206 }
drh20e1f082010-05-31 16:10:12 +00004207 OSTRACE((" - afterwards %03x,%03x\n",
4208 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004209 }
drhd9e5c4f2010-05-12 18:01:39 +00004210#endif
4211
4212 return rc;
4213}
4214
dan781e34c2014-03-20 08:59:47 +00004215/*
dan781e34c2014-03-20 08:59:47 +00004216** Return the minimum number of 32KB shm regions that should be mapped at
4217** a time, assuming that each mapping must be an integer multiple of the
4218** current system page-size.
4219**
4220** Usually, this is 1. The exception seems to be systems that are configured
4221** to use 64KB pages - in this case each mapping must cover at least two
4222** shm regions.
4223*/
4224static int unixShmRegionPerMap(void){
4225 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004226 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004227 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4228 if( pgsz<shmsz ) return 1;
4229 return pgsz/shmsz;
4230}
drhd9e5c4f2010-05-12 18:01:39 +00004231
4232/*
drhd91c68f2010-05-14 14:52:25 +00004233** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004234**
4235** This is not a VFS shared-memory method; it is a utility function called
4236** by VFS shared-memory methods.
4237*/
drhd91c68f2010-05-14 14:52:25 +00004238static void unixShmPurge(unixFile *pFd){
4239 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004240 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004241 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004242 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004243 int i;
drhd91c68f2010-05-14 14:52:25 +00004244 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004245 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004246 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004247 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004248 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004249 }else{
4250 sqlite3_free(p->apRegion[i]);
4251 }
dan13a3cb82010-06-11 19:04:21 +00004252 }
dan18801912010-06-14 14:07:50 +00004253 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004254 if( p->h>=0 ){
4255 robust_close(pFd, p->h, __LINE__);
4256 p->h = -1;
4257 }
drhd91c68f2010-05-14 14:52:25 +00004258 p->pInode->pShmNode = 0;
4259 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004260 }
4261}
4262
4263/*
danda9fe0c2010-07-13 18:44:03 +00004264** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004265** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004266**
drh7234c6d2010-06-19 15:10:09 +00004267** The file used to implement shared-memory is in the same directory
4268** as the open database file and has the same name as the open database
4269** file with the "-shm" suffix added. For example, if the database file
4270** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004271** for shared memory will be called "/home/user1/config.db-shm".
4272**
4273** Another approach to is to use files in /dev/shm or /dev/tmp or an
4274** some other tmpfs mount. But if a file in a different directory
4275** from the database file is used, then differing access permissions
4276** or a chroot() might cause two different processes on the same
4277** database to end up using different files for shared memory -
4278** meaning that their memory would not really be shared - resulting
4279** in database corruption. Nevertheless, this tmpfs file usage
4280** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4281** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4282** option results in an incompatible build of SQLite; builds of SQLite
4283** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4284** same database file at the same time, database corruption will likely
4285** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4286** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004287**
4288** When opening a new shared-memory file, if no other instances of that
4289** file are currently open, in this process or in other processes, then
4290** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004291**
4292** If the original database file (pDbFd) is using the "unix-excl" VFS
4293** that means that an exclusive lock is held on the database file and
4294** that no other processes are able to read or write the database. In
4295** that case, we do not really need shared memory. No shared memory
4296** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004297*/
danda9fe0c2010-07-13 18:44:03 +00004298static int unixOpenSharedMemory(unixFile *pDbFd){
4299 struct unixShm *p = 0; /* The connection to be opened */
4300 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4301 int rc; /* Result code */
4302 unixInodeInfo *pInode; /* The inode of fd */
4303 char *zShmFilename; /* Name of the file used for SHM */
4304 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004305
danda9fe0c2010-07-13 18:44:03 +00004306 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004307 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004308 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004309 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004310 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004311
danda9fe0c2010-07-13 18:44:03 +00004312 /* Check to see if a unixShmNode object already exists. Reuse an existing
4313 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004314 */
4315 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004316 pInode = pDbFd->pInode;
4317 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004318 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004319 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004320#ifndef SQLITE_SHM_DIRECTORY
4321 const char *zBasePath = pDbFd->zPath;
4322#endif
danddb0ac42010-07-14 14:48:58 +00004323
4324 /* Call fstat() to figure out the permissions on the database file. If
4325 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004326 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004327 */
drhf3b1ed02015-12-02 13:11:03 +00004328 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004329 rc = SQLITE_IOERR_FSTAT;
4330 goto shm_open_err;
4331 }
4332
drha4ced192010-07-15 18:32:40 +00004333#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004334 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004335#else
drh4bf66fd2015-02-19 02:43:02 +00004336 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004337#endif
drhf3cdcdc2015-04-29 16:50:28 +00004338 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004339 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004340 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004341 goto shm_open_err;
4342 }
drh9cb5a0d2012-01-05 21:19:54 +00004343 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004344 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004345#ifdef SQLITE_SHM_DIRECTORY
4346 sqlite3_snprintf(nShmFilename, zShmFilename,
4347 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4348 (u32)sStat.st_ino, (u32)sStat.st_dev);
4349#else
drh4bf66fd2015-02-19 02:43:02 +00004350 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004351 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004352#endif
drhd91c68f2010-05-14 14:52:25 +00004353 pShmNode->h = -1;
4354 pDbFd->pInode->pShmNode = pShmNode;
4355 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004356 if( sqlite3GlobalConfig.bCoreMutex ){
4357 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4358 if( pShmNode->mutex==0 ){
4359 rc = SQLITE_NOMEM_BKPT;
4360 goto shm_open_err;
4361 }
drhd91c68f2010-05-14 14:52:25 +00004362 }
drhd9e5c4f2010-05-12 18:01:39 +00004363
drh3cb93392011-03-12 18:10:44 +00004364 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004365 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004366 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004367 openFlags = O_RDONLY;
4368 pShmNode->isReadonly = 1;
4369 }
4370 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004371 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004372 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4373 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004374 }
drhac7c3ac2012-02-11 19:23:48 +00004375
4376 /* If this process is running as root, make sure that the SHM file
4377 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004378 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004379 */
drh6226ca22015-11-24 15:06:28 +00004380 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004381
4382 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004383 ** If not, truncate the file to zero length.
4384 */
4385 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004386 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004387 if( robust_ftruncate(pShmNode->h, 0) ){
4388 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004389 }
4390 }
drh66dfec8b2011-06-01 20:01:49 +00004391 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004392 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004393 }
4394 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004395 }
drhd9e5c4f2010-05-12 18:01:39 +00004396 }
4397
drhd91c68f2010-05-14 14:52:25 +00004398 /* Make the new connection a child of the unixShmNode */
4399 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004400#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004401 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004402#endif
drhd91c68f2010-05-14 14:52:25 +00004403 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004404 pDbFd->pShm = p;
4405 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004406
4407 /* The reference count on pShmNode has already been incremented under
4408 ** the cover of the unixEnterMutex() mutex and the pointer from the
4409 ** new (struct unixShm) object to the pShmNode has been set. All that is
4410 ** left to do is to link the new object into the linked list starting
4411 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4412 ** mutex.
4413 */
4414 sqlite3_mutex_enter(pShmNode->mutex);
4415 p->pNext = pShmNode->pFirst;
4416 pShmNode->pFirst = p;
4417 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004418 return SQLITE_OK;
4419
4420 /* Jump here on any error */
4421shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004422 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004423 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004424 unixLeaveMutex();
4425 return rc;
4426}
4427
4428/*
danda9fe0c2010-07-13 18:44:03 +00004429** This function is called to obtain a pointer to region iRegion of the
4430** shared-memory associated with the database file fd. Shared-memory regions
4431** are numbered starting from zero. Each shared-memory region is szRegion
4432** bytes in size.
4433**
4434** If an error occurs, an error code is returned and *pp is set to NULL.
4435**
4436** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4437** region has not been allocated (by any client, including one running in a
4438** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4439** bExtend is non-zero and the requested shared-memory region has not yet
4440** been allocated, it is allocated by this function.
4441**
4442** If the shared-memory region has already been allocated or is allocated by
4443** this call as described above, then it is mapped into this processes
4444** address space (if it is not already), *pp is set to point to the mapped
4445** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004446*/
danda9fe0c2010-07-13 18:44:03 +00004447static int unixShmMap(
4448 sqlite3_file *fd, /* Handle open on database file */
4449 int iRegion, /* Region to retrieve */
4450 int szRegion, /* Size of regions */
4451 int bExtend, /* True to extend file if necessary */
4452 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004453){
danda9fe0c2010-07-13 18:44:03 +00004454 unixFile *pDbFd = (unixFile*)fd;
4455 unixShm *p;
4456 unixShmNode *pShmNode;
4457 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004458 int nShmPerMap = unixShmRegionPerMap();
4459 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004460
danda9fe0c2010-07-13 18:44:03 +00004461 /* If the shared-memory file has not yet been opened, open it now. */
4462 if( pDbFd->pShm==0 ){
4463 rc = unixOpenSharedMemory(pDbFd);
4464 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004465 }
drhd9e5c4f2010-05-12 18:01:39 +00004466
danda9fe0c2010-07-13 18:44:03 +00004467 p = pDbFd->pShm;
4468 pShmNode = p->pShmNode;
4469 sqlite3_mutex_enter(pShmNode->mutex);
4470 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004471 assert( pShmNode->pInode==pDbFd->pInode );
4472 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4473 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004474
dan781e34c2014-03-20 08:59:47 +00004475 /* Minimum number of regions required to be mapped. */
4476 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4477
4478 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004479 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004480 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004481 struct stat sStat; /* Used by fstat() */
4482
4483 pShmNode->szRegion = szRegion;
4484
drh3cb93392011-03-12 18:10:44 +00004485 if( pShmNode->h>=0 ){
4486 /* The requested region is not mapped into this processes address space.
4487 ** Check to see if it has been allocated (i.e. if the wal-index file is
4488 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004489 */
drh3cb93392011-03-12 18:10:44 +00004490 if( osFstat(pShmNode->h, &sStat) ){
4491 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004492 goto shmpage_out;
4493 }
drh3cb93392011-03-12 18:10:44 +00004494
4495 if( sStat.st_size<nByte ){
4496 /* The requested memory region does not exist. If bExtend is set to
4497 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004498 */
dan47a2b4a2013-04-26 16:09:29 +00004499 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004500 goto shmpage_out;
4501 }
dan47a2b4a2013-04-26 16:09:29 +00004502
4503 /* Alternatively, if bExtend is true, extend the file. Do this by
4504 ** writing a single byte to the end of each (OS) page being
4505 ** allocated or extended. Technically, we need only write to the
4506 ** last page in order to extend the file. But writing to all new
4507 ** pages forces the OS to allocate them immediately, which reduces
4508 ** the chances of SIGBUS while accessing the mapped region later on.
4509 */
4510 else{
4511 static const int pgsz = 4096;
4512 int iPg;
4513
4514 /* Write to the last byte of each newly allocated or extended page */
4515 assert( (nByte % pgsz)==0 );
4516 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004517 int x = 0;
4518 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004519 const char *zFile = pShmNode->zFilename;
4520 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4521 goto shmpage_out;
4522 }
4523 }
drh3cb93392011-03-12 18:10:44 +00004524 }
4525 }
danda9fe0c2010-07-13 18:44:03 +00004526 }
4527
4528 /* Map the requested memory region into this processes address space. */
4529 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004530 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004531 );
4532 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004533 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004534 goto shmpage_out;
4535 }
4536 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004537 while( pShmNode->nRegion<nReqRegion ){
4538 int nMap = szRegion*nShmPerMap;
4539 int i;
drh3cb93392011-03-12 18:10:44 +00004540 void *pMem;
4541 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004542 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004543 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004544 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004545 );
4546 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004547 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004548 goto shmpage_out;
4549 }
4550 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004551 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004552 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004553 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004554 goto shmpage_out;
4555 }
4556 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004557 }
dan781e34c2014-03-20 08:59:47 +00004558
4559 for(i=0; i<nShmPerMap; i++){
4560 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4561 }
4562 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004563 }
4564 }
4565
4566shmpage_out:
4567 if( pShmNode->nRegion>iRegion ){
4568 *pp = pShmNode->apRegion[iRegion];
4569 }else{
4570 *pp = 0;
4571 }
drh66dfec8b2011-06-01 20:01:49 +00004572 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004573 sqlite3_mutex_leave(pShmNode->mutex);
4574 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004575}
4576
4577/*
drhd9e5c4f2010-05-12 18:01:39 +00004578** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004579**
4580** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4581** different here than in posix. In xShmLock(), one can go from unlocked
4582** to shared and back or from unlocked to exclusive and back. But one may
4583** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004584*/
4585static int unixShmLock(
4586 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004587 int ofst, /* First lock to acquire or release */
4588 int n, /* Number of locks to acquire or release */
4589 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004590){
drh73b64e42010-05-30 19:55:15 +00004591 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4592 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4593 unixShm *pX; /* For looping over all siblings */
4594 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4595 int rc = SQLITE_OK; /* Result code */
4596 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004597
drhd91c68f2010-05-14 14:52:25 +00004598 assert( pShmNode==pDbFd->pInode->pShmNode );
4599 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004600 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004601 assert( n>=1 );
4602 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4603 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4604 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4605 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4606 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004607 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4608 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004609
drhc99597c2010-05-31 01:41:15 +00004610 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004611 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004612 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004613 if( flags & SQLITE_SHM_UNLOCK ){
4614 u16 allMask = 0; /* Mask of locks held by siblings */
4615
4616 /* See if any siblings hold this same lock */
4617 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4618 if( pX==p ) continue;
4619 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4620 allMask |= pX->sharedMask;
4621 }
4622
4623 /* Unlock the system-level locks */
4624 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004625 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004626 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004627 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004628 }
drh73b64e42010-05-30 19:55:15 +00004629
4630 /* Undo the local locks */
4631 if( rc==SQLITE_OK ){
4632 p->exclMask &= ~mask;
4633 p->sharedMask &= ~mask;
4634 }
4635 }else if( flags & SQLITE_SHM_SHARED ){
4636 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4637
4638 /* Find out which shared locks are already held by sibling connections.
4639 ** If any sibling already holds an exclusive lock, go ahead and return
4640 ** SQLITE_BUSY.
4641 */
4642 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004643 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004644 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004645 break;
4646 }
4647 allShared |= pX->sharedMask;
4648 }
4649
4650 /* Get shared locks at the system level, if necessary */
4651 if( rc==SQLITE_OK ){
4652 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004653 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004654 }else{
drh73b64e42010-05-30 19:55:15 +00004655 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004656 }
drhd9e5c4f2010-05-12 18:01:39 +00004657 }
drh73b64e42010-05-30 19:55:15 +00004658
4659 /* Get the local shared locks */
4660 if( rc==SQLITE_OK ){
4661 p->sharedMask |= mask;
4662 }
4663 }else{
4664 /* Make sure no sibling connections hold locks that will block this
4665 ** lock. If any do, return SQLITE_BUSY right away.
4666 */
4667 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004668 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4669 rc = SQLITE_BUSY;
4670 break;
4671 }
4672 }
4673
4674 /* Get the exclusive locks at the system level. Then if successful
4675 ** also mark the local connection as being locked.
4676 */
4677 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004678 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004679 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004680 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004681 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004682 }
drhd9e5c4f2010-05-12 18:01:39 +00004683 }
4684 }
drhd91c68f2010-05-14 14:52:25 +00004685 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004686 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004687 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004688 return rc;
4689}
4690
drh286a2882010-05-20 23:51:06 +00004691/*
4692** Implement a memory barrier or memory fence on shared memory.
4693**
4694** All loads and stores begun before the barrier must complete before
4695** any load or store begun after the barrier.
4696*/
4697static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004698 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004699){
drhff828942010-06-26 21:34:06 +00004700 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004701 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4702 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004703 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004704}
4705
dan18801912010-06-14 14:07:50 +00004706/*
danda9fe0c2010-07-13 18:44:03 +00004707** Close a connection to shared-memory. Delete the underlying
4708** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004709**
4710** If there is no shared memory associated with the connection then this
4711** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004712*/
danda9fe0c2010-07-13 18:44:03 +00004713static int unixShmUnmap(
4714 sqlite3_file *fd, /* The underlying database file */
4715 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004716){
danda9fe0c2010-07-13 18:44:03 +00004717 unixShm *p; /* The connection to be closed */
4718 unixShmNode *pShmNode; /* The underlying shared-memory file */
4719 unixShm **pp; /* For looping over sibling connections */
4720 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004721
danda9fe0c2010-07-13 18:44:03 +00004722 pDbFd = (unixFile*)fd;
4723 p = pDbFd->pShm;
4724 if( p==0 ) return SQLITE_OK;
4725 pShmNode = p->pShmNode;
4726
4727 assert( pShmNode==pDbFd->pInode->pShmNode );
4728 assert( pShmNode->pInode==pDbFd->pInode );
4729
4730 /* Remove connection p from the set of connections associated
4731 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004732 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004733 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4734 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004735
danda9fe0c2010-07-13 18:44:03 +00004736 /* Free the connection p */
4737 sqlite3_free(p);
4738 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004739 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004740
4741 /* If pShmNode->nRef has reached 0, then close the underlying
4742 ** shared-memory file, too */
4743 unixEnterMutex();
4744 assert( pShmNode->nRef>0 );
4745 pShmNode->nRef--;
4746 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004747 if( deleteFlag && pShmNode->h>=0 ){
4748 osUnlink(pShmNode->zFilename);
4749 }
danda9fe0c2010-07-13 18:44:03 +00004750 unixShmPurge(pDbFd);
4751 }
4752 unixLeaveMutex();
4753
4754 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004755}
drh286a2882010-05-20 23:51:06 +00004756
danda9fe0c2010-07-13 18:44:03 +00004757
drhd9e5c4f2010-05-12 18:01:39 +00004758#else
drh6b017cc2010-06-14 18:01:46 +00004759# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004760# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004761# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004762# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004763#endif /* #ifndef SQLITE_OMIT_WAL */
4764
mistachkine98844f2013-08-24 00:59:24 +00004765#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004766/*
danaef49d72013-03-25 16:28:54 +00004767** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004768*/
danf23da962013-03-23 21:00:41 +00004769static void unixUnmapfile(unixFile *pFd){
4770 assert( pFd->nFetchOut==0 );
4771 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004772 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004773 pFd->pMapRegion = 0;
4774 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004775 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004776 }
4777}
dan5d8a1372013-03-19 19:28:06 +00004778
danaef49d72013-03-25 16:28:54 +00004779/*
dane6ecd662013-04-01 17:56:59 +00004780** Attempt to set the size of the memory mapping maintained by file
4781** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4782**
4783** If successful, this function sets the following variables:
4784**
4785** unixFile.pMapRegion
4786** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004787** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004788**
4789** If unsuccessful, an error message is logged via sqlite3_log() and
4790** the three variables above are zeroed. In this case SQLite should
4791** continue accessing the database using the xRead() and xWrite()
4792** methods.
4793*/
4794static void unixRemapfile(
4795 unixFile *pFd, /* File descriptor object */
4796 i64 nNew /* Required mapping size */
4797){
dan4ff7bc42013-04-02 12:04:09 +00004798 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004799 int h = pFd->h; /* File descriptor open on db file */
4800 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004801 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004802 u8 *pNew = 0; /* Location of new mapping */
4803 int flags = PROT_READ; /* Flags to pass to mmap() */
4804
4805 assert( pFd->nFetchOut==0 );
4806 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004807 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004808 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004809 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004810 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004811
danfe33e392015-11-17 20:56:06 +00004812#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004813 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004814#endif
dane6ecd662013-04-01 17:56:59 +00004815
4816 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004817#if HAVE_MREMAP
4818 i64 nReuse = pFd->mmapSize;
4819#else
danbc760632014-03-20 09:42:09 +00004820 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004821 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004822#endif
dane6ecd662013-04-01 17:56:59 +00004823 u8 *pReq = &pOrig[nReuse];
4824
4825 /* Unmap any pages of the existing mapping that cannot be reused. */
4826 if( nReuse!=nOrig ){
4827 osMunmap(pReq, nOrig-nReuse);
4828 }
4829
4830#if HAVE_MREMAP
4831 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004832 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004833#else
4834 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4835 if( pNew!=MAP_FAILED ){
4836 if( pNew!=pReq ){
4837 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004838 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004839 }else{
4840 pNew = pOrig;
4841 }
4842 }
4843#endif
4844
dan48ccef82013-04-02 20:55:01 +00004845 /* The attempt to extend the existing mapping failed. Free it. */
4846 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004847 osMunmap(pOrig, nReuse);
4848 }
4849 }
4850
4851 /* If pNew is still NULL, try to create an entirely new mapping. */
4852 if( pNew==0 ){
4853 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004854 }
4855
dan4ff7bc42013-04-02 12:04:09 +00004856 if( pNew==MAP_FAILED ){
4857 pNew = 0;
4858 nNew = 0;
4859 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4860
4861 /* If the mmap() above failed, assume that all subsequent mmap() calls
4862 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4863 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004864 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004865 }
dane6ecd662013-04-01 17:56:59 +00004866 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004867 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004868}
4869
4870/*
danaef49d72013-03-25 16:28:54 +00004871** Memory map or remap the file opened by file-descriptor pFd (if the file
4872** is already mapped, the existing mapping is replaced by the new). Or, if
4873** there already exists a mapping for this file, and there are still
4874** outstanding xFetch() references to it, this function is a no-op.
4875**
4876** If parameter nByte is non-negative, then it is the requested size of
4877** the mapping to create. Otherwise, if nByte is less than zero, then the
4878** requested size is the size of the file on disk. The actual size of the
4879** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004880** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004881**
4882** SQLITE_OK is returned if no error occurs (even if the mapping is not
4883** recreated as a result of outstanding references) or an SQLite error
4884** code otherwise.
4885*/
drhf3b1ed02015-12-02 13:11:03 +00004886static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004887 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004888 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004889 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4890
4891 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004892 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004893 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004894 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004895 }
drh3044b512014-06-16 16:41:52 +00004896 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004897 }
drh9b4c59f2013-04-15 17:03:42 +00004898 if( nMap>pFd->mmapSizeMax ){
4899 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004900 }
4901
drh333e6ca2015-12-02 15:44:39 +00004902 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004903 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004904 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004905 }
4906
danf23da962013-03-23 21:00:41 +00004907 return SQLITE_OK;
4908}
mistachkine98844f2013-08-24 00:59:24 +00004909#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004910
danaef49d72013-03-25 16:28:54 +00004911/*
4912** If possible, return a pointer to a mapping of file fd starting at offset
4913** iOff. The mapping must be valid for at least nAmt bytes.
4914**
4915** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4916** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4917** Finally, if an error does occur, return an SQLite error code. The final
4918** value of *pp is undefined in this case.
4919**
4920** If this function does return a pointer, the caller must eventually
4921** release the reference by calling unixUnfetch().
4922*/
danf23da962013-03-23 21:00:41 +00004923static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004924#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004925 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004926#endif
danf23da962013-03-23 21:00:41 +00004927 *pp = 0;
4928
drh9b4c59f2013-04-15 17:03:42 +00004929#if SQLITE_MAX_MMAP_SIZE>0
4930 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004931 if( pFd->pMapRegion==0 ){
4932 int rc = unixMapfile(pFd, -1);
4933 if( rc!=SQLITE_OK ) return rc;
4934 }
4935 if( pFd->mmapSize >= iOff+nAmt ){
4936 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4937 pFd->nFetchOut++;
4938 }
4939 }
drh6e0b6d52013-04-09 16:19:20 +00004940#endif
danf23da962013-03-23 21:00:41 +00004941 return SQLITE_OK;
4942}
4943
danaef49d72013-03-25 16:28:54 +00004944/*
dandf737fe2013-03-25 17:00:24 +00004945** If the third argument is non-NULL, then this function releases a
4946** reference obtained by an earlier call to unixFetch(). The second
4947** argument passed to this function must be the same as the corresponding
4948** argument that was passed to the unixFetch() invocation.
4949**
4950** Or, if the third argument is NULL, then this function is being called
4951** to inform the VFS layer that, according to POSIX, any existing mapping
4952** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004953*/
dandf737fe2013-03-25 17:00:24 +00004954static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004955#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004956 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004957 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004958
danaef49d72013-03-25 16:28:54 +00004959 /* If p==0 (unmap the entire file) then there must be no outstanding
4960 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4961 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004962 assert( (p==0)==(pFd->nFetchOut==0) );
4963
dandf737fe2013-03-25 17:00:24 +00004964 /* If p!=0, it must match the iOff value. */
4965 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4966
danf23da962013-03-23 21:00:41 +00004967 if( p ){
4968 pFd->nFetchOut--;
4969 }else{
4970 unixUnmapfile(pFd);
4971 }
4972
4973 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004974#else
4975 UNUSED_PARAMETER(fd);
4976 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004977 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004978#endif
danf23da962013-03-23 21:00:41 +00004979 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004980}
4981
4982/*
drh734c9862008-11-28 15:37:20 +00004983** Here ends the implementation of all sqlite3_file methods.
4984**
4985********************** End sqlite3_file Methods *******************************
4986******************************************************************************/
4987
4988/*
drh6b9d6dd2008-12-03 19:34:47 +00004989** This division contains definitions of sqlite3_io_methods objects that
4990** implement various file locking strategies. It also contains definitions
4991** of "finder" functions. A finder-function is used to locate the appropriate
4992** sqlite3_io_methods object for a particular database file. The pAppData
4993** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4994** the correct finder-function for that VFS.
4995**
4996** Most finder functions return a pointer to a fixed sqlite3_io_methods
4997** object. The only interesting finder-function is autolockIoFinder, which
4998** looks at the filesystem type and tries to guess the best locking
4999** strategy from that.
5000**
peter.d.reid60ec9142014-09-06 16:39:46 +00005001** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005002**
5003** (1) The real finder-function named "FImpt()".
5004**
dane946c392009-08-22 11:39:46 +00005005** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005006**
5007**
5008** A pointer to the F pointer is used as the pAppData value for VFS
5009** objects. We have to do this instead of letting pAppData point
5010** directly at the finder-function since C90 rules prevent a void*
5011** from be cast into a function pointer.
5012**
drh6b9d6dd2008-12-03 19:34:47 +00005013**
drh7708e972008-11-29 00:56:52 +00005014** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005015**
drh7708e972008-11-29 00:56:52 +00005016** * A constant sqlite3_io_methods object call METHOD that has locking
5017** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5018**
5019** * An I/O method finder function called FINDER that returns a pointer
5020** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005021*/
drhe6d41732015-02-21 00:49:00 +00005022#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005023static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005024 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005025 CLOSE, /* xClose */ \
5026 unixRead, /* xRead */ \
5027 unixWrite, /* xWrite */ \
5028 unixTruncate, /* xTruncate */ \
5029 unixSync, /* xSync */ \
5030 unixFileSize, /* xFileSize */ \
5031 LOCK, /* xLock */ \
5032 UNLOCK, /* xUnlock */ \
5033 CKLOCK, /* xCheckReservedLock */ \
5034 unixFileControl, /* xFileControl */ \
5035 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005036 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005037 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005038 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005039 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005040 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005041 unixFetch, /* xFetch */ \
5042 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005043}; \
drh0c2694b2009-09-03 16:23:44 +00005044static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5045 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005046 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005047} \
drh0c2694b2009-09-03 16:23:44 +00005048static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005049 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005050
5051/*
5052** Here are all of the sqlite3_io_methods objects for each of the
5053** locking strategies. Functions that return pointers to these methods
5054** are also created.
5055*/
5056IOMETHODS(
5057 posixIoFinder, /* Finder function name */
5058 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005059 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005060 unixClose, /* xClose method */
5061 unixLock, /* xLock method */
5062 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005063 unixCheckReservedLock, /* xCheckReservedLock method */
5064 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005065)
drh7708e972008-11-29 00:56:52 +00005066IOMETHODS(
5067 nolockIoFinder, /* Finder function name */
5068 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005069 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005070 nolockClose, /* xClose method */
5071 nolockLock, /* xLock method */
5072 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005073 nolockCheckReservedLock, /* xCheckReservedLock method */
5074 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005075)
drh7708e972008-11-29 00:56:52 +00005076IOMETHODS(
5077 dotlockIoFinder, /* Finder function name */
5078 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005079 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005080 dotlockClose, /* xClose method */
5081 dotlockLock, /* xLock method */
5082 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005083 dotlockCheckReservedLock, /* xCheckReservedLock method */
5084 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005085)
drh7708e972008-11-29 00:56:52 +00005086
drhe89b2912015-03-03 20:42:01 +00005087#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005088IOMETHODS(
5089 flockIoFinder, /* Finder function name */
5090 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005091 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005092 flockClose, /* xClose method */
5093 flockLock, /* xLock method */
5094 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005095 flockCheckReservedLock, /* xCheckReservedLock method */
5096 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005097)
drh7708e972008-11-29 00:56:52 +00005098#endif
5099
drh6c7d5c52008-11-21 20:32:33 +00005100#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005101IOMETHODS(
5102 semIoFinder, /* Finder function name */
5103 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005104 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005105 semXClose, /* xClose method */
5106 semXLock, /* xLock method */
5107 semXUnlock, /* xUnlock method */
5108 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005109 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005110)
aswiftaebf4132008-11-21 00:10:35 +00005111#endif
drh7708e972008-11-29 00:56:52 +00005112
drhd2cb50b2009-01-09 21:41:17 +00005113#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005114IOMETHODS(
5115 afpIoFinder, /* Finder function name */
5116 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005117 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005118 afpClose, /* xClose method */
5119 afpLock, /* xLock method */
5120 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005121 afpCheckReservedLock, /* xCheckReservedLock method */
5122 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005123)
drh715ff302008-12-03 22:32:44 +00005124#endif
5125
5126/*
5127** The proxy locking method is a "super-method" in the sense that it
5128** opens secondary file descriptors for the conch and lock files and
5129** it uses proxy, dot-file, AFP, and flock() locking methods on those
5130** secondary files. For this reason, the division that implements
5131** proxy locking is located much further down in the file. But we need
5132** to go ahead and define the sqlite3_io_methods and finder function
5133** for proxy locking here. So we forward declare the I/O methods.
5134*/
drhd2cb50b2009-01-09 21:41:17 +00005135#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005136static int proxyClose(sqlite3_file*);
5137static int proxyLock(sqlite3_file*, int);
5138static int proxyUnlock(sqlite3_file*, int);
5139static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005140IOMETHODS(
5141 proxyIoFinder, /* Finder function name */
5142 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005143 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005144 proxyClose, /* xClose method */
5145 proxyLock, /* xLock method */
5146 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005147 proxyCheckReservedLock, /* xCheckReservedLock method */
5148 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005149)
aswiftaebf4132008-11-21 00:10:35 +00005150#endif
drh7708e972008-11-29 00:56:52 +00005151
drh7ed97b92010-01-20 13:07:21 +00005152/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5153#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5154IOMETHODS(
5155 nfsIoFinder, /* Finder function name */
5156 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005157 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005158 unixClose, /* xClose method */
5159 unixLock, /* xLock method */
5160 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005161 unixCheckReservedLock, /* xCheckReservedLock method */
5162 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005163)
5164#endif
drh7708e972008-11-29 00:56:52 +00005165
drhd2cb50b2009-01-09 21:41:17 +00005166#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005167/*
drh6b9d6dd2008-12-03 19:34:47 +00005168** This "finder" function attempts to determine the best locking strategy
5169** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005170** object that implements that strategy.
5171**
5172** This is for MacOSX only.
5173*/
drh1875f7a2008-12-08 18:19:17 +00005174static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005175 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005176 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005177){
5178 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005179 const char *zFilesystem; /* Filesystem type name */
5180 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005181 } aMap[] = {
5182 { "hfs", &posixIoMethods },
5183 { "ufs", &posixIoMethods },
5184 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005185 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005186 { "webdav", &nolockIoMethods },
5187 { 0, 0 }
5188 };
5189 int i;
5190 struct statfs fsInfo;
5191 struct flock lockInfo;
5192
5193 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005194 /* If filePath==NULL that means we are dealing with a transient file
5195 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005196 return &nolockIoMethods;
5197 }
5198 if( statfs(filePath, &fsInfo) != -1 ){
5199 if( fsInfo.f_flags & MNT_RDONLY ){
5200 return &nolockIoMethods;
5201 }
5202 for(i=0; aMap[i].zFilesystem; i++){
5203 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5204 return aMap[i].pMethods;
5205 }
5206 }
5207 }
5208
5209 /* Default case. Handles, amongst others, "nfs".
5210 ** Test byte-range lock using fcntl(). If the call succeeds,
5211 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005212 */
drh7708e972008-11-29 00:56:52 +00005213 lockInfo.l_len = 1;
5214 lockInfo.l_start = 0;
5215 lockInfo.l_whence = SEEK_SET;
5216 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005217 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005218 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5219 return &nfsIoMethods;
5220 } else {
5221 return &posixIoMethods;
5222 }
drh7708e972008-11-29 00:56:52 +00005223 }else{
5224 return &dotlockIoMethods;
5225 }
5226}
drh0c2694b2009-09-03 16:23:44 +00005227static const sqlite3_io_methods
5228 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005229
drhd2cb50b2009-01-09 21:41:17 +00005230#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005231
drhe89b2912015-03-03 20:42:01 +00005232#if OS_VXWORKS
5233/*
5234** This "finder" function for VxWorks checks to see if posix advisory
5235** locking works. If it does, then that is what is used. If it does not
5236** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005237*/
drhe89b2912015-03-03 20:42:01 +00005238static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005239 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005240 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005241){
5242 struct flock lockInfo;
5243
5244 if( !filePath ){
5245 /* If filePath==NULL that means we are dealing with a transient file
5246 ** that does not need to be locked. */
5247 return &nolockIoMethods;
5248 }
5249
5250 /* Test if fcntl() is supported and use POSIX style locks.
5251 ** Otherwise fall back to the named semaphore method.
5252 */
5253 lockInfo.l_len = 1;
5254 lockInfo.l_start = 0;
5255 lockInfo.l_whence = SEEK_SET;
5256 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005257 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005258 return &posixIoMethods;
5259 }else{
5260 return &semIoMethods;
5261 }
5262}
drh0c2694b2009-09-03 16:23:44 +00005263static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005264 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005265
drhe89b2912015-03-03 20:42:01 +00005266#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005267
drh7708e972008-11-29 00:56:52 +00005268/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005269** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005270*/
drh0c2694b2009-09-03 16:23:44 +00005271typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005272
aswiftaebf4132008-11-21 00:10:35 +00005273
drh734c9862008-11-28 15:37:20 +00005274/****************************************************************************
5275**************************** sqlite3_vfs methods ****************************
5276**
5277** This division contains the implementation of methods on the
5278** sqlite3_vfs object.
5279*/
5280
danielk1977a3d4c882007-03-23 10:08:38 +00005281/*
danielk1977e339d652008-06-28 11:23:00 +00005282** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005283*/
5284static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005285 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005286 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005287 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005288 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005289 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005290){
drh7708e972008-11-29 00:56:52 +00005291 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005292 unixFile *pNew = (unixFile *)pId;
5293 int rc = SQLITE_OK;
5294
drh8af6c222010-05-14 12:43:01 +00005295 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005296
dan00157392010-10-05 11:33:15 +00005297 /* Usually the path zFilename should not be a relative pathname. The
5298 ** exception is when opening the proxy "conch" file in builds that
5299 ** include the special Apple locking styles.
5300 */
dan00157392010-10-05 11:33:15 +00005301#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005302 assert( zFilename==0 || zFilename[0]=='/'
5303 || pVfs->pAppData==(void*)&autolockIoFinder );
5304#else
5305 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005306#endif
dan00157392010-10-05 11:33:15 +00005307
drhb07028f2011-10-14 21:49:18 +00005308 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005309 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005310
drh308c2a52010-05-14 11:30:18 +00005311 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005312 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005313 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005314 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005315 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005316#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005317 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005318#endif
drhc02a43a2012-01-10 23:18:38 +00005319 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5320 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005321 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005322 }
drh503a6862013-03-01 01:07:17 +00005323 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005324 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005325 }
drh339eb0b2008-03-07 15:34:11 +00005326
drh6c7d5c52008-11-21 20:32:33 +00005327#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005328 pNew->pId = vxworksFindFileId(zFilename);
5329 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005330 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005331 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005332 }
5333#endif
5334
drhc02a43a2012-01-10 23:18:38 +00005335 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005336 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005337 }else{
drh0c2694b2009-09-03 16:23:44 +00005338 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005339#if SQLITE_ENABLE_LOCKING_STYLE
5340 /* Cache zFilename in the locking context (AFP and dotlock override) for
5341 ** proxyLock activation is possible (remote proxy is based on db name)
5342 ** zFilename remains valid until file is closed, to support */
5343 pNew->lockingContext = (void*)zFilename;
5344#endif
drhda0e7682008-07-30 15:27:54 +00005345 }
danielk1977e339d652008-06-28 11:23:00 +00005346
drh7ed97b92010-01-20 13:07:21 +00005347 if( pLockingStyle == &posixIoMethods
5348#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5349 || pLockingStyle == &nfsIoMethods
5350#endif
5351 ){
drh7708e972008-11-29 00:56:52 +00005352 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005353 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005354 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005355 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005356 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005357 ** in two scenarios:
5358 **
5359 ** (a) A call to fstat() failed.
5360 ** (b) A malloc failed.
5361 **
5362 ** Scenario (b) may only occur if the process is holding no other
5363 ** file descriptors open on the same file. If there were other file
5364 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005365 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005366 ** handle h - as it is guaranteed that no posix locks will be released
5367 ** by doing so.
5368 **
5369 ** If scenario (a) caused the error then things are not so safe. The
5370 ** implicit assumption here is that if fstat() fails, things are in
5371 ** such bad shape that dropping a lock or two doesn't matter much.
5372 */
drh0e9365c2011-03-02 02:08:13 +00005373 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005374 h = -1;
5375 }
drh7708e972008-11-29 00:56:52 +00005376 unixLeaveMutex();
5377 }
danielk1977e339d652008-06-28 11:23:00 +00005378
drhd2cb50b2009-01-09 21:41:17 +00005379#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005380 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005381 /* AFP locking uses the file path so it needs to be included in
5382 ** the afpLockingContext.
5383 */
5384 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005385 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005386 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005387 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005388 }else{
5389 /* NB: zFilename exists and remains valid until the file is closed
5390 ** according to requirement F11141. So we do not need to make a
5391 ** copy of the filename. */
5392 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005393 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005394 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005395 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005396 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005397 if( rc!=SQLITE_OK ){
5398 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005399 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005400 h = -1;
5401 }
drh7708e972008-11-29 00:56:52 +00005402 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005403 }
drh7708e972008-11-29 00:56:52 +00005404 }
5405#endif
danielk1977e339d652008-06-28 11:23:00 +00005406
drh7708e972008-11-29 00:56:52 +00005407 else if( pLockingStyle == &dotlockIoMethods ){
5408 /* Dotfile locking uses the file path so it needs to be included in
5409 ** the dotlockLockingContext
5410 */
5411 char *zLockFile;
5412 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005413 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005414 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005415 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005416 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005417 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005418 }else{
5419 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005420 }
drh7708e972008-11-29 00:56:52 +00005421 pNew->lockingContext = zLockFile;
5422 }
danielk1977e339d652008-06-28 11:23:00 +00005423
drh6c7d5c52008-11-21 20:32:33 +00005424#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005425 else if( pLockingStyle == &semIoMethods ){
5426 /* Named semaphore locking uses the file path so it needs to be
5427 ** included in the semLockingContext
5428 */
5429 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005430 rc = findInodeInfo(pNew, &pNew->pInode);
5431 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5432 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005433 int n;
drh2238dcc2009-08-27 17:56:20 +00005434 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005435 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005436 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005437 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005438 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5439 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005440 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005441 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005442 }
chw97185482008-11-17 08:05:31 +00005443 }
drh7708e972008-11-29 00:56:52 +00005444 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005445 }
drh7708e972008-11-29 00:56:52 +00005446#endif
aswift5b1a2562008-08-22 00:22:35 +00005447
drh4bf66fd2015-02-19 02:43:02 +00005448 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005449#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005450 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005451 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005452 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005453 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005454 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005455 }
chw97185482008-11-17 08:05:31 +00005456#endif
danielk1977e339d652008-06-28 11:23:00 +00005457 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005458 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005459 }else{
drh7708e972008-11-29 00:56:52 +00005460 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005461 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005462 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005463 }
danielk1977e339d652008-06-28 11:23:00 +00005464 return rc;
drh054889e2005-11-30 03:20:31 +00005465}
drh9c06c952005-11-26 00:25:00 +00005466
danielk1977ad94b582007-08-20 06:44:22 +00005467/*
drh8b3cf822010-06-01 21:02:51 +00005468** Return the name of a directory in which to put temporary files.
5469** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005470*/
drh7234c6d2010-06-19 15:10:09 +00005471static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005472 static const char *azDirs[] = {
5473 0,
aswiftaebf4132008-11-21 00:10:35 +00005474 0,
danielk197717b90b52008-06-06 11:11:25 +00005475 "/var/tmp",
5476 "/usr/tmp",
5477 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005478 "."
danielk197717b90b52008-06-06 11:11:25 +00005479 };
drh2aab11f2016-04-29 20:30:56 +00005480 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005481 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005482 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005483
drhb7e50ad2015-11-28 21:49:53 +00005484 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5485 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005486 while(1){
5487 if( zDir!=0
5488 && osStat(zDir, &buf)==0
5489 && S_ISDIR(buf.st_mode)
5490 && osAccess(zDir, 03)==0
5491 ){
5492 return zDir;
5493 }
5494 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5495 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005496 }
drh7694e062016-04-21 23:37:24 +00005497 return 0;
drh8b3cf822010-06-01 21:02:51 +00005498}
5499
5500/*
5501** Create a temporary file name in zBuf. zBuf must be allocated
5502** by the calling process and must be big enough to hold at least
5503** pVfs->mxPathname bytes.
5504*/
5505static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005506 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005507 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005508
5509 /* It's odd to simulate an io-error here, but really this is just
5510 ** using the io-error infrastructure to test that SQLite handles this
5511 ** function failing.
5512 */
drh7694e062016-04-21 23:37:24 +00005513 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005514 SimulateIOError( return SQLITE_IOERR );
5515
drh7234c6d2010-06-19 15:10:09 +00005516 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005517 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005518 do{
drh970942e2015-11-25 23:13:14 +00005519 u64 r;
5520 sqlite3_randomness(sizeof(r), &r);
5521 assert( nBuf>2 );
5522 zBuf[nBuf-2] = 0;
5523 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5524 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005525 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005526 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005527 return SQLITE_OK;
5528}
5529
drhd2cb50b2009-01-09 21:41:17 +00005530#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005531/*
5532** Routine to transform a unixFile into a proxy-locking unixFile.
5533** Implementation in the proxy-lock division, but used by unixOpen()
5534** if SQLITE_PREFER_PROXY_LOCKING is defined.
5535*/
5536static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005537#endif
drhc66d5b62008-12-03 22:48:32 +00005538
dan08da86a2009-08-21 17:18:03 +00005539/*
5540** Search for an unused file descriptor that was opened on the database
5541** file (not a journal or master-journal file) identified by pathname
5542** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5543** argument to this function.
5544**
5545** Such a file descriptor may exist if a database connection was closed
5546** but the associated file descriptor could not be closed because some
5547** other file descriptor open on the same file is holding a file-lock.
5548** Refer to comments in the unixClose() function and the lengthy comment
5549** describing "Posix Advisory Locking" at the start of this file for
5550** further details. Also, ticket #4018.
5551**
5552** If a suitable file descriptor is found, then it is returned. If no
5553** such file descriptor is located, -1 is returned.
5554*/
dane946c392009-08-22 11:39:46 +00005555static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5556 UnixUnusedFd *pUnused = 0;
5557
5558 /* Do not search for an unused file descriptor on vxworks. Not because
5559 ** vxworks would not benefit from the change (it might, we're not sure),
5560 ** but because no way to test it is currently available. It is better
5561 ** not to risk breaking vxworks support for the sake of such an obscure
5562 ** feature. */
5563#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005564 struct stat sStat; /* Results of stat() call */
5565
5566 /* A stat() call may fail for various reasons. If this happens, it is
5567 ** almost certain that an open() call on the same path will also fail.
5568 ** For this reason, if an error occurs in the stat() call here, it is
5569 ** ignored and -1 is returned. The caller will try to open a new file
5570 ** descriptor on the same path, fail, and return an error to SQLite.
5571 **
5572 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005573 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005574 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005575 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005576
5577 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005578 pInode = inodeList;
5579 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005580 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005581 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005582 }
drh8af6c222010-05-14 12:43:01 +00005583 if( pInode ){
dane946c392009-08-22 11:39:46 +00005584 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005585 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005586 pUnused = *pp;
5587 if( pUnused ){
5588 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005589 }
5590 }
5591 unixLeaveMutex();
5592 }
dane946c392009-08-22 11:39:46 +00005593#endif /* if !OS_VXWORKS */
5594 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005595}
danielk197717b90b52008-06-06 11:11:25 +00005596
5597/*
dan1bf4ca72016-08-11 18:05:47 +00005598** Find the mode, uid and gid of file zFile.
5599*/
5600static int getFileMode(
5601 const char *zFile, /* File name */
5602 mode_t *pMode, /* OUT: Permissions of zFile */
5603 uid_t *pUid, /* OUT: uid of zFile. */
5604 gid_t *pGid /* OUT: gid of zFile. */
5605){
5606 struct stat sStat; /* Output of stat() on database file */
5607 int rc = SQLITE_OK;
5608 if( 0==osStat(zFile, &sStat) ){
5609 *pMode = sStat.st_mode & 0777;
5610 *pUid = sStat.st_uid;
5611 *pGid = sStat.st_gid;
5612 }else{
5613 rc = SQLITE_IOERR_FSTAT;
5614 }
5615 return rc;
5616}
5617
5618/*
danddb0ac42010-07-14 14:48:58 +00005619** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005620** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005621** and a value suitable for passing as the third argument to open(2) is
5622** written to *pMode. If an IO error occurs, an SQLite error code is
5623** returned and the value of *pMode is not modified.
5624**
peter.d.reid60ec9142014-09-06 16:39:46 +00005625** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005626** an indication to robust_open() to create the file using
5627** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5628** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005629** this function queries the file-system for the permissions on the
5630** corresponding database file and sets *pMode to this value. Whenever
5631** possible, WAL and journal files are created using the same permissions
5632** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005633**
5634** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5635** original filename is unavailable. But 8_3_NAMES is only used for
5636** FAT filesystems and permissions do not matter there, so just use
5637** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005638*/
5639static int findCreateFileMode(
5640 const char *zPath, /* Path of file (possibly) being created */
5641 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005642 mode_t *pMode, /* OUT: Permissions to open file with */
5643 uid_t *pUid, /* OUT: uid to set on the file */
5644 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005645){
5646 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005647 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005648 *pUid = 0;
5649 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005650 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005651 char zDb[MAX_PATHNAME+1]; /* Database file path */
5652 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005653
dana0c989d2010-11-05 18:07:37 +00005654 /* zPath is a path to a WAL or journal file. The following block derives
5655 ** the path to the associated database file from zPath. This block handles
5656 ** the following naming conventions:
5657 **
5658 ** "<path to db>-journal"
5659 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005660 ** "<path to db>-journalNN"
5661 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005662 **
drhd337c5b2011-10-20 18:23:35 +00005663 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005664 ** used by the test_multiplex.c module.
5665 */
5666 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005667 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005668#ifndef SQLITE_ENABLE_8_3_NAMES
5669 /* In the normal case (8+3 filenames disabled) the journal filename
5670 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005671 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005672 assert( sqlite3Isalnum(zPath[nDb]) );
5673#else
5674 /* If 8+3 names are possible, then the journal file might not contain
5675 ** a '-' character. So check for that case and return early. */
5676 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5677#endif
drhc47167a2011-10-05 15:26:13 +00005678 nDb--;
5679 }
danddb0ac42010-07-14 14:48:58 +00005680 memcpy(zDb, zPath, nDb);
5681 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005682
dan1bf4ca72016-08-11 18:05:47 +00005683 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005684 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5685 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005686 }else if( flags & SQLITE_OPEN_URI ){
5687 /* If this is a main database file and the file was opened using a URI
5688 ** filename, check for the "modeof" parameter. If present, interpret
5689 ** its value as a filename and try to copy the mode, uid and gid from
5690 ** that file. */
5691 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5692 if( z ){
5693 rc = getFileMode(z, pMode, pUid, pGid);
5694 }
danddb0ac42010-07-14 14:48:58 +00005695 }
5696 return rc;
5697}
5698
5699/*
danielk1977ad94b582007-08-20 06:44:22 +00005700** Open the file zPath.
5701**
danielk1977b4b47412007-08-17 15:53:36 +00005702** Previously, the SQLite OS layer used three functions in place of this
5703** one:
5704**
5705** sqlite3OsOpenReadWrite();
5706** sqlite3OsOpenReadOnly();
5707** sqlite3OsOpenExclusive();
5708**
5709** These calls correspond to the following combinations of flags:
5710**
5711** ReadWrite() -> (READWRITE | CREATE)
5712** ReadOnly() -> (READONLY)
5713** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5714**
5715** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5716** true, the file was configured to be automatically deleted when the
5717** file handle closed. To achieve the same effect using this new
5718** interface, add the DELETEONCLOSE flag to those specified above for
5719** OpenExclusive().
5720*/
5721static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005722 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5723 const char *zPath, /* Pathname of file to be opened */
5724 sqlite3_file *pFile, /* The file descriptor to be filled in */
5725 int flags, /* Input flags to control the opening */
5726 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005727){
dan08da86a2009-08-21 17:18:03 +00005728 unixFile *p = (unixFile *)pFile;
5729 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005730 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005731 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005732 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005733 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005734 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005735
5736 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5737 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5738 int isCreate = (flags & SQLITE_OPEN_CREATE);
5739 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5740 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005741#if SQLITE_ENABLE_LOCKING_STYLE
5742 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5743#endif
drh3d4435b2011-08-26 20:55:50 +00005744#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5745 struct statfs fsInfo;
5746#endif
danielk1977b4b47412007-08-17 15:53:36 +00005747
danielk1977fee2d252007-08-18 10:59:19 +00005748 /* If creating a master or main-file journal, this function will open
5749 ** a file-descriptor on the directory too. The first time unixSync()
5750 ** is called the directory file descriptor will be fsync()ed and close()d.
5751 */
drh0059eae2011-08-08 23:48:40 +00005752 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005753 eType==SQLITE_OPEN_MASTER_JOURNAL
5754 || eType==SQLITE_OPEN_MAIN_JOURNAL
5755 || eType==SQLITE_OPEN_WAL
5756 ));
danielk1977fee2d252007-08-18 10:59:19 +00005757
danielk197717b90b52008-06-06 11:11:25 +00005758 /* If argument zPath is a NULL pointer, this function is required to open
5759 ** a temporary file. Use this buffer to store the file name in.
5760 */
drhc02a43a2012-01-10 23:18:38 +00005761 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005762 const char *zName = zPath;
5763
danielk1977fee2d252007-08-18 10:59:19 +00005764 /* Check the following statements are true:
5765 **
5766 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5767 ** (b) if CREATE is set, then READWRITE must also be set, and
5768 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005769 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005770 */
danielk1977b4b47412007-08-17 15:53:36 +00005771 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005772 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005773 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005774 assert(isDelete==0 || isCreate);
5775
danddb0ac42010-07-14 14:48:58 +00005776 /* The main DB, main journal, WAL file and master journal are never
5777 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005778 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5779 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5780 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005781 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005782
danielk1977fee2d252007-08-18 10:59:19 +00005783 /* Assert that the upper layer has set one of the "file-type" flags. */
5784 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5785 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5786 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005787 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005788 );
5789
drhb00d8622014-01-01 15:18:36 +00005790 /* Detect a pid change and reset the PRNG. There is a race condition
5791 ** here such that two or more threads all trying to open databases at
5792 ** the same instant might all reset the PRNG. But multiple resets
5793 ** are harmless.
5794 */
drh5ac93652015-03-21 20:59:43 +00005795 if( randomnessPid!=osGetpid(0) ){
5796 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005797 sqlite3_randomness(0,0);
5798 }
5799
dan08da86a2009-08-21 17:18:03 +00005800 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005801
dan08da86a2009-08-21 17:18:03 +00005802 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005803 UnixUnusedFd *pUnused;
5804 pUnused = findReusableFd(zName, flags);
5805 if( pUnused ){
5806 fd = pUnused->fd;
5807 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005808 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005809 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005810 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005811 }
5812 }
5813 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005814
5815 /* Database filenames are double-zero terminated if they are not
5816 ** URIs with parameters. Hence, they can always be passed into
5817 ** sqlite3_uri_parameter(). */
5818 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5819
dan08da86a2009-08-21 17:18:03 +00005820 }else if( !zName ){
5821 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005822 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005823 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005824 if( rc!=SQLITE_OK ){
5825 return rc;
5826 }
5827 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005828
5829 /* Generated temporary filenames are always double-zero terminated
5830 ** for use by sqlite3_uri_parameter(). */
5831 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005832 }
5833
dan08da86a2009-08-21 17:18:03 +00005834 /* Determine the value of the flags parameter passed to POSIX function
5835 ** open(). These must be calculated even if open() is not called, as
5836 ** they may be stored as part of the file handle and used by the
5837 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005838 if( isReadonly ) openFlags |= O_RDONLY;
5839 if( isReadWrite ) openFlags |= O_RDWR;
5840 if( isCreate ) openFlags |= O_CREAT;
5841 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5842 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005843
danielk1977b4b47412007-08-17 15:53:36 +00005844 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005845 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005846 uid_t uid; /* Userid for the file */
5847 gid_t gid; /* Groupid for the file */
5848 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005849 if( rc!=SQLITE_OK ){
5850 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005851 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005852 return rc;
5853 }
drhad4f1e52011-03-04 15:43:57 +00005854 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005855 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005856 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5857 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005858 /* Failed to open the file for read/write access. Try read-only. */
5859 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005860 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005861 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005862 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005863 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005864 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005865 }
5866 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005867 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005868 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005869 }
drhac7c3ac2012-02-11 19:23:48 +00005870
5871 /* If this process is running as root and if creating a new rollback
5872 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005873 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005874 */
5875 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005876 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005877 }
danielk1977b4b47412007-08-17 15:53:36 +00005878 }
dan08da86a2009-08-21 17:18:03 +00005879 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005880 if( pOutFlags ){
5881 *pOutFlags = flags;
5882 }
5883
dane946c392009-08-22 11:39:46 +00005884 if( p->pUnused ){
5885 p->pUnused->fd = fd;
5886 p->pUnused->flags = flags;
5887 }
5888
danielk1977b4b47412007-08-17 15:53:36 +00005889 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005890#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005891 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005892#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5893 zPath = sqlite3_mprintf("%s", zName);
5894 if( zPath==0 ){
5895 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00005896 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00005897 }
chw97185482008-11-17 08:05:31 +00005898#else
drh036ac7f2011-08-08 23:18:05 +00005899 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005900#endif
danielk1977b4b47412007-08-17 15:53:36 +00005901 }
drh41022642008-11-21 00:24:42 +00005902#if SQLITE_ENABLE_LOCKING_STYLE
5903 else{
dan08da86a2009-08-21 17:18:03 +00005904 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005905 }
5906#endif
drh7ed97b92010-01-20 13:07:21 +00005907
5908#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005909 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005910 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005911 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005912 return SQLITE_IOERR_ACCESS;
5913 }
5914 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5915 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5916 }
drh4bf66fd2015-02-19 02:43:02 +00005917 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5918 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5919 }
drh7ed97b92010-01-20 13:07:21 +00005920#endif
drhc02a43a2012-01-10 23:18:38 +00005921
5922 /* Set up appropriate ctrlFlags */
5923 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5924 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00005925 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00005926 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5927 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5928 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5929
drh7ed97b92010-01-20 13:07:21 +00005930#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005931#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005932 isAutoProxy = 1;
5933#endif
5934 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005935 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5936 int useProxy = 0;
5937
dan08da86a2009-08-21 17:18:03 +00005938 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5939 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005940 if( envforce!=NULL ){
5941 useProxy = atoi(envforce)>0;
5942 }else{
aswiftaebf4132008-11-21 00:10:35 +00005943 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5944 }
5945 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005946 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005947 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005948 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005949 if( rc!=SQLITE_OK ){
5950 /* Use unixClose to clean up the resources added in fillInUnixFile
5951 ** and clear all the structure's references. Specifically,
5952 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5953 */
5954 unixClose(pFile);
5955 return rc;
5956 }
aswiftaebf4132008-11-21 00:10:35 +00005957 }
dane946c392009-08-22 11:39:46 +00005958 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005959 }
5960 }
5961#endif
5962
drhc02a43a2012-01-10 23:18:38 +00005963 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5964
dane946c392009-08-22 11:39:46 +00005965open_finished:
5966 if( rc!=SQLITE_OK ){
5967 sqlite3_free(p->pUnused);
5968 }
5969 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005970}
5971
dane946c392009-08-22 11:39:46 +00005972
danielk1977b4b47412007-08-17 15:53:36 +00005973/*
danielk1977fee2d252007-08-18 10:59:19 +00005974** Delete the file at zPath. If the dirSync argument is true, fsync()
5975** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005976*/
drh6b9d6dd2008-12-03 19:34:47 +00005977static int unixDelete(
5978 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5979 const char *zPath, /* Name of file to be deleted */
5980 int dirSync /* If true, fsync() directory after deleting file */
5981){
danielk1977fee2d252007-08-18 10:59:19 +00005982 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005983 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005984 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005985 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005986 if( errno==ENOENT
5987#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005988 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005989#endif
5990 ){
dan9fc5b4a2012-11-09 20:17:26 +00005991 rc = SQLITE_IOERR_DELETE_NOENT;
5992 }else{
drhb4308162012-11-09 21:40:02 +00005993 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005994 }
drhb4308162012-11-09 21:40:02 +00005995 return rc;
drh5d4feff2010-07-14 01:45:22 +00005996 }
danielk1977d39fa702008-10-16 13:27:40 +00005997#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005998 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005999 int fd;
drh90315a22011-08-10 01:52:12 +00006000 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006001 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006002 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006003 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006004 }
drh0e9365c2011-03-02 02:08:13 +00006005 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006006 }else{
6007 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006008 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006009 }
6010 }
danielk1977d138dd82008-10-15 16:02:48 +00006011#endif
danielk1977fee2d252007-08-18 10:59:19 +00006012 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006013}
6014
danielk197790949c22007-08-17 16:50:38 +00006015/*
mistachkin48864df2013-03-21 21:20:32 +00006016** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006017** test performed depends on the value of flags:
6018**
6019** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6020** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6021** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6022**
6023** Otherwise return 0.
6024*/
danielk1977861f7452008-06-05 11:39:11 +00006025static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006026 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6027 const char *zPath, /* Path of the file to examine */
6028 int flags, /* What do we want to learn about the zPath file? */
6029 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006030){
danielk1977397d65f2008-11-19 11:35:39 +00006031 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006032 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006033 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006034
drhd260b5b2015-11-25 18:03:33 +00006035 /* The spec says there are three possible values for flags. But only
6036 ** two of them are actually used */
6037 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6038
6039 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006040 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006041 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6042 }else{
6043 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006044 }
danielk1977861f7452008-06-05 11:39:11 +00006045 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006046}
6047
danielk1977b4b47412007-08-17 15:53:36 +00006048/*
danielk1977b4b47412007-08-17 15:53:36 +00006049**
danielk1977b4b47412007-08-17 15:53:36 +00006050*/
dane88ec182016-01-25 17:04:48 +00006051static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006052 const char *zPath, /* Input path */
6053 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006054 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006055){
dancaf6b152016-01-25 18:05:49 +00006056 int nPath = sqlite3Strlen30(zPath);
6057 int iOff = 0;
6058 if( zPath[0]!='/' ){
6059 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006060 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006061 }
dancaf6b152016-01-25 18:05:49 +00006062 iOff = sqlite3Strlen30(zOut);
6063 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006064 }
dan23496702016-01-26 13:56:42 +00006065 if( (iOff+nPath+1)>nOut ){
6066 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6067 ** even if it returns an error. */
6068 zOut[iOff] = '\0';
6069 return SQLITE_CANTOPEN_BKPT;
6070 }
dancaf6b152016-01-25 18:05:49 +00006071 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006072 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006073}
6074
dane88ec182016-01-25 17:04:48 +00006075/*
6076** Turn a relative pathname into a full pathname. The relative path
6077** is stored as a nul-terminated string in the buffer pointed to by
6078** zPath.
6079**
6080** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6081** (in this case, MAX_PATHNAME bytes). The full-path is written to
6082** this buffer before returning.
6083*/
6084static int unixFullPathname(
6085 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6086 const char *zPath, /* Possibly relative input path */
6087 int nOut, /* Size of output buffer in bytes */
6088 char *zOut /* Output buffer */
6089){
danaf1b36b2016-01-25 18:43:05 +00006090#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006091 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006092#else
6093 int rc = SQLITE_OK;
6094 int nByte;
dancaf6b152016-01-25 18:05:49 +00006095 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006096 const char *zIn = zPath; /* Input path for each iteration of loop */
6097 char *zDel = 0;
6098
6099 assert( pVfs->mxPathname==MAX_PATHNAME );
6100 UNUSED_PARAMETER(pVfs);
6101
6102 /* It's odd to simulate an io-error here, but really this is just
6103 ** using the io-error infrastructure to test that SQLite handles this
6104 ** function failing. This function could fail if, for example, the
6105 ** current working directory has been unlinked.
6106 */
6107 SimulateIOError( return SQLITE_ERROR );
6108
6109 do {
6110
dancaf6b152016-01-25 18:05:49 +00006111 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6112 ** link, or false otherwise. */
6113 int bLink = 0;
6114 struct stat buf;
6115 if( osLstat(zIn, &buf)!=0 ){
6116 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006117 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006118 }
dane88ec182016-01-25 17:04:48 +00006119 }else{
dancaf6b152016-01-25 18:05:49 +00006120 bLink = S_ISLNK(buf.st_mode);
6121 }
6122
6123 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006124 if( zDel==0 ){
6125 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006126 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006127 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6128 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006129 }
dancaf6b152016-01-25 18:05:49 +00006130
6131 if( rc==SQLITE_OK ){
6132 nByte = osReadlink(zIn, zDel, nOut-1);
6133 if( nByte<0 ){
6134 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006135 }else{
6136 if( zDel[0]!='/' ){
6137 int n;
6138 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6139 if( nByte+n+1>nOut ){
6140 rc = SQLITE_CANTOPEN_BKPT;
6141 }else{
6142 memmove(&zDel[n], zDel, nByte+1);
6143 memcpy(zDel, zIn, n);
6144 nByte += n;
6145 }
dancaf6b152016-01-25 18:05:49 +00006146 }
6147 zDel[nByte] = '\0';
6148 }
6149 }
6150
6151 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006152 }
6153
dan23496702016-01-26 13:56:42 +00006154 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6155 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006156 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006157 }
dancaf6b152016-01-25 18:05:49 +00006158 if( bLink==0 ) break;
6159 zIn = zOut;
6160 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006161
6162 sqlite3_free(zDel);
6163 return rc;
danaf1b36b2016-01-25 18:43:05 +00006164#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006165}
6166
drh0ccebe72005-06-07 22:22:50 +00006167
drh761df872006-12-21 01:29:22 +00006168#ifndef SQLITE_OMIT_LOAD_EXTENSION
6169/*
6170** Interfaces for opening a shared library, finding entry points
6171** within the shared library, and closing the shared library.
6172*/
6173#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006174static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6175 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006176 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6177}
danielk197795c8a542007-09-01 06:51:27 +00006178
6179/*
6180** SQLite calls this function immediately after a call to unixDlSym() or
6181** unixDlOpen() fails (returns a null pointer). If a more detailed error
6182** message is available, it is written to zBufOut. If no error message
6183** is available, zBufOut is left unmodified and SQLite uses a default
6184** error message.
6185*/
danielk1977397d65f2008-11-19 11:35:39 +00006186static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006187 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006188 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006189 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006190 zErr = dlerror();
6191 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006192 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006193 }
drh6c7d5c52008-11-21 20:32:33 +00006194 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006195}
drh1875f7a2008-12-08 18:19:17 +00006196static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6197 /*
6198 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6199 ** cast into a pointer to a function. And yet the library dlsym() routine
6200 ** returns a void* which is really a pointer to a function. So how do we
6201 ** use dlsym() with -pedantic-errors?
6202 **
6203 ** Variable x below is defined to be a pointer to a function taking
6204 ** parameters void* and const char* and returning a pointer to a function.
6205 ** We initialize x by assigning it a pointer to the dlsym() function.
6206 ** (That assignment requires a cast.) Then we call the function that
6207 ** x points to.
6208 **
6209 ** This work-around is unlikely to work correctly on any system where
6210 ** you really cannot cast a function pointer into void*. But then, on the
6211 ** other hand, dlsym() will not work on such a system either, so we have
6212 ** not really lost anything.
6213 */
6214 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006215 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006216 x = (void(*(*)(void*,const char*))(void))dlsym;
6217 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006218}
danielk1977397d65f2008-11-19 11:35:39 +00006219static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6220 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006221 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006222}
danielk1977b4b47412007-08-17 15:53:36 +00006223#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6224 #define unixDlOpen 0
6225 #define unixDlError 0
6226 #define unixDlSym 0
6227 #define unixDlClose 0
6228#endif
6229
6230/*
danielk197790949c22007-08-17 16:50:38 +00006231** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006232*/
danielk1977397d65f2008-11-19 11:35:39 +00006233static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6234 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006235 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006236
drhbbd42a62004-05-22 17:41:58 +00006237 /* We have to initialize zBuf to prevent valgrind from reporting
6238 ** errors. The reports issued by valgrind are incorrect - we would
6239 ** prefer that the randomness be increased by making use of the
6240 ** uninitialized space in zBuf - but valgrind errors tend to worry
6241 ** some users. Rather than argue, it seems easier just to initialize
6242 ** the whole array and silence valgrind, even if that means less randomness
6243 ** in the random seed.
6244 **
6245 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006246 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006247 ** tests repeatable.
6248 */
danielk1977b4b47412007-08-17 15:53:36 +00006249 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006250 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006251#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006252 {
drhb00d8622014-01-01 15:18:36 +00006253 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006254 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006255 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006256 time_t t;
6257 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006258 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006259 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6260 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6261 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006262 }else{
drhc18b4042012-02-10 03:10:27 +00006263 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006264 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006265 }
drhbbd42a62004-05-22 17:41:58 +00006266 }
6267#endif
drh72cbd072008-10-14 17:58:38 +00006268 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006269}
6270
danielk1977b4b47412007-08-17 15:53:36 +00006271
drhbbd42a62004-05-22 17:41:58 +00006272/*
6273** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006274** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006275** The return value is the number of microseconds of sleep actually
6276** requested from the underlying operating system, a number which
6277** might be greater than or equal to the argument, but not less
6278** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006279*/
danielk1977397d65f2008-11-19 11:35:39 +00006280static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006281#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006282 struct timespec sp;
6283
6284 sp.tv_sec = microseconds / 1000000;
6285 sp.tv_nsec = (microseconds % 1000000) * 1000;
6286 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006287 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006288 return microseconds;
6289#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006290 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006291 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006292 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006293#else
danielk1977b4b47412007-08-17 15:53:36 +00006294 int seconds = (microseconds+999999)/1000000;
6295 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006296 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006297 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006298#endif
drh88f474a2006-01-02 20:00:12 +00006299}
6300
6301/*
drh6b9d6dd2008-12-03 19:34:47 +00006302** The following variable, if set to a non-zero value, is interpreted as
6303** the number of seconds since 1970 and is used to set the result of
6304** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006305*/
6306#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006307int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006308#endif
6309
6310/*
drhb7e8ea22010-05-03 14:32:30 +00006311** Find the current time (in Universal Coordinated Time). Write into *piNow
6312** the current time and date as a Julian Day number times 86_400_000. In
6313** other words, write into *piNow the number of milliseconds since the Julian
6314** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6315** proleptic Gregorian calendar.
6316**
drh31702252011-10-12 23:13:43 +00006317** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6318** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006319*/
6320static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6321 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006322 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006323#if defined(NO_GETTOD)
6324 time_t t;
6325 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006326 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006327#elif OS_VXWORKS
6328 struct timespec sNow;
6329 clock_gettime(CLOCK_REALTIME, &sNow);
6330 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6331#else
6332 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006333 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6334 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006335#endif
6336
6337#ifdef SQLITE_TEST
6338 if( sqlite3_current_time ){
6339 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6340 }
6341#endif
6342 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006343 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006344}
6345
drhc3dfa5e2016-01-22 19:44:03 +00006346#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006347/*
drhbbd42a62004-05-22 17:41:58 +00006348** Find the current time (in Universal Coordinated Time). Write the
6349** current time and date as a Julian Day number into *prNow and
6350** return 0. Return 1 if the time and date cannot be found.
6351*/
danielk1977397d65f2008-11-19 11:35:39 +00006352static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006353 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006354 int rc;
drhff828942010-06-26 21:34:06 +00006355 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006356 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006357 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006358 return rc;
drhbbd42a62004-05-22 17:41:58 +00006359}
drh5337dac2015-11-25 15:15:03 +00006360#else
6361# define unixCurrentTime 0
6362#endif
danielk1977b4b47412007-08-17 15:53:36 +00006363
drh6b9d6dd2008-12-03 19:34:47 +00006364/*
drh1b9f2142016-03-17 16:01:23 +00006365** The xGetLastError() method is designed to return a better
6366** low-level error message when operating-system problems come up
6367** during SQLite operation. Only the integer return code is currently
6368** used.
drh6b9d6dd2008-12-03 19:34:47 +00006369*/
danielk1977397d65f2008-11-19 11:35:39 +00006370static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6371 UNUSED_PARAMETER(NotUsed);
6372 UNUSED_PARAMETER(NotUsed2);
6373 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006374 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006375}
6376
drhf2424c52010-04-26 00:04:55 +00006377
6378/*
drh734c9862008-11-28 15:37:20 +00006379************************ End of sqlite3_vfs methods ***************************
6380******************************************************************************/
6381
drh715ff302008-12-03 22:32:44 +00006382/******************************************************************************
6383************************** Begin Proxy Locking ********************************
6384**
6385** Proxy locking is a "uber-locking-method" in this sense: It uses the
6386** other locking methods on secondary lock files. Proxy locking is a
6387** meta-layer over top of the primitive locking implemented above. For
6388** this reason, the division that implements of proxy locking is deferred
6389** until late in the file (here) after all of the other I/O methods have
6390** been defined - so that the primitive locking methods are available
6391** as services to help with the implementation of proxy locking.
6392**
6393****
6394**
6395** The default locking schemes in SQLite use byte-range locks on the
6396** database file to coordinate safe, concurrent access by multiple readers
6397** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6398** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6399** as POSIX read & write locks over fixed set of locations (via fsctl),
6400** on AFP and SMB only exclusive byte-range locks are available via fsctl
6401** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6402** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6403** address in the shared range is taken for a SHARED lock, the entire
6404** shared range is taken for an EXCLUSIVE lock):
6405**
drhf2f105d2012-08-20 15:53:54 +00006406** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006407** RESERVED_BYTE 0x40000001
6408** SHARED_RANGE 0x40000002 -> 0x40000200
6409**
6410** This works well on the local file system, but shows a nearly 100x
6411** slowdown in read performance on AFP because the AFP client disables
6412** the read cache when byte-range locks are present. Enabling the read
6413** cache exposes a cache coherency problem that is present on all OS X
6414** supported network file systems. NFS and AFP both observe the
6415** close-to-open semantics for ensuring cache coherency
6416** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6417** address the requirements for concurrent database access by multiple
6418** readers and writers
6419** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6420**
6421** To address the performance and cache coherency issues, proxy file locking
6422** changes the way database access is controlled by limiting access to a
6423** single host at a time and moving file locks off of the database file
6424** and onto a proxy file on the local file system.
6425**
6426**
6427** Using proxy locks
6428** -----------------
6429**
6430** C APIs
6431**
drh4bf66fd2015-02-19 02:43:02 +00006432** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006433** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006434** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6435** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006436**
6437**
6438** SQL pragmas
6439**
6440** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6441** PRAGMA [database.]lock_proxy_file
6442**
6443** Specifying ":auto:" means that if there is a conch file with a matching
6444** host ID in it, the proxy path in the conch file will be used, otherwise
6445** a proxy path based on the user's temp dir
6446** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6447** actual proxy file name is generated from the name and path of the
6448** database file. For example:
6449**
6450** For database path "/Users/me/foo.db"
6451** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6452**
6453** Once a lock proxy is configured for a database connection, it can not
6454** be removed, however it may be switched to a different proxy path via
6455** the above APIs (assuming the conch file is not being held by another
6456** connection or process).
6457**
6458**
6459** How proxy locking works
6460** -----------------------
6461**
6462** Proxy file locking relies primarily on two new supporting files:
6463**
6464** * conch file to limit access to the database file to a single host
6465** at a time
6466**
6467** * proxy file to act as a proxy for the advisory locks normally
6468** taken on the database
6469**
6470** The conch file - to use a proxy file, sqlite must first "hold the conch"
6471** by taking an sqlite-style shared lock on the conch file, reading the
6472** contents and comparing the host's unique host ID (see below) and lock
6473** proxy path against the values stored in the conch. The conch file is
6474** stored in the same directory as the database file and the file name
6475** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006476** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006477** host ID and/or proxy path, then the lock is escalated to an exclusive
6478** lock and the conch file contents is updated with the host ID and proxy
6479** path and the lock is downgraded to a shared lock again. If the conch
6480** is held by another process (with a shared lock), the exclusive lock
6481** will fail and SQLITE_BUSY is returned.
6482**
6483** The proxy file - a single-byte file used for all advisory file locks
6484** normally taken on the database file. This allows for safe sharing
6485** of the database file for multiple readers and writers on the same
6486** host (the conch ensures that they all use the same local lock file).
6487**
drh715ff302008-12-03 22:32:44 +00006488** Requesting the lock proxy does not immediately take the conch, it is
6489** only taken when the first request to lock database file is made.
6490** This matches the semantics of the traditional locking behavior, where
6491** opening a connection to a database file does not take a lock on it.
6492** The shared lock and an open file descriptor are maintained until
6493** the connection to the database is closed.
6494**
6495** The proxy file and the lock file are never deleted so they only need
6496** to be created the first time they are used.
6497**
6498** Configuration options
6499** ---------------------
6500**
6501** SQLITE_PREFER_PROXY_LOCKING
6502**
6503** Database files accessed on non-local file systems are
6504** automatically configured for proxy locking, lock files are
6505** named automatically using the same logic as
6506** PRAGMA lock_proxy_file=":auto:"
6507**
6508** SQLITE_PROXY_DEBUG
6509**
6510** Enables the logging of error messages during host id file
6511** retrieval and creation
6512**
drh715ff302008-12-03 22:32:44 +00006513** LOCKPROXYDIR
6514**
6515** Overrides the default directory used for lock proxy files that
6516** are named automatically via the ":auto:" setting
6517**
6518** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6519**
6520** Permissions to use when creating a directory for storing the
6521** lock proxy files, only used when LOCKPROXYDIR is not set.
6522**
6523**
6524** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6525** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6526** force proxy locking to be used for every database file opened, and 0
6527** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006528** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006529** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6530*/
6531
6532/*
6533** Proxy locking is only available on MacOSX
6534*/
drhd2cb50b2009-01-09 21:41:17 +00006535#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006536
drh715ff302008-12-03 22:32:44 +00006537/*
6538** The proxyLockingContext has the path and file structures for the remote
6539** and local proxy files in it
6540*/
6541typedef struct proxyLockingContext proxyLockingContext;
6542struct proxyLockingContext {
6543 unixFile *conchFile; /* Open conch file */
6544 char *conchFilePath; /* Name of the conch file */
6545 unixFile *lockProxy; /* Open proxy lock file */
6546 char *lockProxyPath; /* Name of the proxy lock file */
6547 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006548 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006549 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006550 void *oldLockingContext; /* Original lockingcontext to restore on close */
6551 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6552};
6553
drh7ed97b92010-01-20 13:07:21 +00006554/*
6555** The proxy lock file path for the database at dbPath is written into lPath,
6556** which must point to valid, writable memory large enough for a maxLen length
6557** file path.
drh715ff302008-12-03 22:32:44 +00006558*/
drh715ff302008-12-03 22:32:44 +00006559static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6560 int len;
6561 int dbLen;
6562 int i;
6563
6564#ifdef LOCKPROXYDIR
6565 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6566#else
6567# ifdef _CS_DARWIN_USER_TEMP_DIR
6568 {
drh7ed97b92010-01-20 13:07:21 +00006569 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006570 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006571 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006572 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006573 }
drh7ed97b92010-01-20 13:07:21 +00006574 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006575 }
6576# else
6577 len = strlcpy(lPath, "/tmp/", maxLen);
6578# endif
6579#endif
6580
6581 if( lPath[len-1]!='/' ){
6582 len = strlcat(lPath, "/", maxLen);
6583 }
6584
6585 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006586 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006587 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006588 char c = dbPath[i];
6589 lPath[i+len] = (c=='/')?'_':c;
6590 }
6591 lPath[i+len]='\0';
6592 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006593 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006594 return SQLITE_OK;
6595}
6596
drh7ed97b92010-01-20 13:07:21 +00006597/*
6598 ** Creates the lock file and any missing directories in lockPath
6599 */
6600static int proxyCreateLockPath(const char *lockPath){
6601 int i, len;
6602 char buf[MAXPATHLEN];
6603 int start = 0;
6604
6605 assert(lockPath!=NULL);
6606 /* try to create all the intermediate directories */
6607 len = (int)strlen(lockPath);
6608 buf[0] = lockPath[0];
6609 for( i=1; i<len; i++ ){
6610 if( lockPath[i] == '/' && (i - start > 0) ){
6611 /* only mkdir if leaf dir != "." or "/" or ".." */
6612 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6613 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6614 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006615 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006616 int err=errno;
6617 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006618 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006619 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006620 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006621 return err;
6622 }
6623 }
6624 }
6625 start=i+1;
6626 }
6627 buf[i] = lockPath[i];
6628 }
drh62aaa6c2015-11-21 17:27:42 +00006629 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006630 return 0;
6631}
6632
drh715ff302008-12-03 22:32:44 +00006633/*
6634** Create a new VFS file descriptor (stored in memory obtained from
6635** sqlite3_malloc) and open the file named "path" in the file descriptor.
6636**
6637** The caller is responsible not only for closing the file descriptor
6638** but also for freeing the memory associated with the file descriptor.
6639*/
drh7ed97b92010-01-20 13:07:21 +00006640static int proxyCreateUnixFile(
6641 const char *path, /* path for the new unixFile */
6642 unixFile **ppFile, /* unixFile created and returned by ref */
6643 int islockfile /* if non zero missing dirs will be created */
6644) {
6645 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006646 unixFile *pNew;
6647 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006648 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006649 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006650 int terrno = 0;
6651 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006652
drh7ed97b92010-01-20 13:07:21 +00006653 /* 1. first try to open/create the file
6654 ** 2. if that fails, and this is a lock file (not-conch), try creating
6655 ** the parent directories and then try again.
6656 ** 3. if that fails, try to open the file read-only
6657 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6658 */
6659 pUnused = findReusableFd(path, openFlags);
6660 if( pUnused ){
6661 fd = pUnused->fd;
6662 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006663 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006664 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006665 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006666 }
6667 }
6668 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006669 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006670 terrno = errno;
6671 if( fd<0 && errno==ENOENT && islockfile ){
6672 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006673 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006674 }
6675 }
6676 }
6677 if( fd<0 ){
6678 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006679 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006680 terrno = errno;
6681 }
6682 if( fd<0 ){
6683 if( islockfile ){
6684 return SQLITE_BUSY;
6685 }
6686 switch (terrno) {
6687 case EACCES:
6688 return SQLITE_PERM;
6689 case EIO:
6690 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6691 default:
drh9978c972010-02-23 17:36:32 +00006692 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006693 }
6694 }
6695
drhf3cdcdc2015-04-29 16:50:28 +00006696 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006697 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006698 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006699 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006700 }
6701 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006702 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006703 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006704 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006705 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006706 pUnused->fd = fd;
6707 pUnused->flags = openFlags;
6708 pNew->pUnused = pUnused;
6709
drhc02a43a2012-01-10 23:18:38 +00006710 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006711 if( rc==SQLITE_OK ){
6712 *ppFile = pNew;
6713 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006714 }
drh7ed97b92010-01-20 13:07:21 +00006715end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006716 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006717 sqlite3_free(pNew);
6718 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006719 return rc;
6720}
6721
drh7ed97b92010-01-20 13:07:21 +00006722#ifdef SQLITE_TEST
6723/* simulate multiple hosts by creating unique hostid file paths */
6724int sqlite3_hostid_num = 0;
6725#endif
6726
6727#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6728
drh6bca6512015-04-13 23:05:28 +00006729#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006730/* Not always defined in the headers as it ought to be */
6731extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006732#endif
drh0ab216a2010-07-02 17:10:40 +00006733
drh7ed97b92010-01-20 13:07:21 +00006734/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6735** bytes of writable memory.
6736*/
6737static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006738 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6739 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006740#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006741 {
drh4bf66fd2015-02-19 02:43:02 +00006742 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006743 if( gethostuuid(pHostID, &timeout) ){
6744 int err = errno;
6745 if( pError ){
6746 *pError = err;
6747 }
6748 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006749 }
drh7ed97b92010-01-20 13:07:21 +00006750 }
drh3d4435b2011-08-26 20:55:50 +00006751#else
6752 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006753#endif
drh7ed97b92010-01-20 13:07:21 +00006754#ifdef SQLITE_TEST
6755 /* simulate multiple hosts by creating unique hostid file paths */
6756 if( sqlite3_hostid_num != 0){
6757 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6758 }
6759#endif
6760
6761 return SQLITE_OK;
6762}
6763
6764/* The conch file contains the header, host id and lock file path
6765 */
6766#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6767#define PROXY_HEADERLEN 1 /* conch file header length */
6768#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6769#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6770
6771/*
6772** Takes an open conch file, copies the contents to a new path and then moves
6773** it back. The newly created file's file descriptor is assigned to the
6774** conch file structure and finally the original conch file descriptor is
6775** closed. Returns zero if successful.
6776*/
6777static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6778 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6779 unixFile *conchFile = pCtx->conchFile;
6780 char tPath[MAXPATHLEN];
6781 char buf[PROXY_MAXCONCHLEN];
6782 char *cPath = pCtx->conchFilePath;
6783 size_t readLen = 0;
6784 size_t pathLen = 0;
6785 char errmsg[64] = "";
6786 int fd = -1;
6787 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006788 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006789
6790 /* create a new path by replace the trailing '-conch' with '-break' */
6791 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6792 if( pathLen>MAXPATHLEN || pathLen<6 ||
6793 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006794 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006795 goto end_breaklock;
6796 }
6797 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006798 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006799 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006800 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006801 goto end_breaklock;
6802 }
6803 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006804 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006805 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006806 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006807 goto end_breaklock;
6808 }
drhe562be52011-03-02 18:01:10 +00006809 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006810 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006811 goto end_breaklock;
6812 }
6813 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006814 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006815 goto end_breaklock;
6816 }
6817 rc = 0;
6818 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006819 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006820 conchFile->h = fd;
6821 conchFile->openFlags = O_RDWR | O_CREAT;
6822
6823end_breaklock:
6824 if( rc ){
6825 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006826 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006827 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006828 }
6829 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6830 }
6831 return rc;
6832}
6833
6834/* Take the requested lock on the conch file and break a stale lock if the
6835** host id matches.
6836*/
6837static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6838 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6839 unixFile *conchFile = pCtx->conchFile;
6840 int rc = SQLITE_OK;
6841 int nTries = 0;
6842 struct timespec conchModTime;
6843
drh3d4435b2011-08-26 20:55:50 +00006844 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006845 do {
6846 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6847 nTries ++;
6848 if( rc==SQLITE_BUSY ){
6849 /* If the lock failed (busy):
6850 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6851 * 2nd try: fail if the mod time changed or host id is different, wait
6852 * 10 sec and try again
6853 * 3rd try: break the lock unless the mod time has changed.
6854 */
6855 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006856 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006857 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006858 return SQLITE_IOERR_LOCK;
6859 }
6860
6861 if( nTries==1 ){
6862 conchModTime = buf.st_mtimespec;
6863 usleep(500000); /* wait 0.5 sec and try the lock again*/
6864 continue;
6865 }
6866
6867 assert( nTries>1 );
6868 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6869 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6870 return SQLITE_BUSY;
6871 }
6872
6873 if( nTries==2 ){
6874 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006875 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006876 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006877 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006878 return SQLITE_IOERR_LOCK;
6879 }
6880 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6881 /* don't break the lock if the host id doesn't match */
6882 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6883 return SQLITE_BUSY;
6884 }
6885 }else{
6886 /* don't break the lock on short read or a version mismatch */
6887 return SQLITE_BUSY;
6888 }
6889 usleep(10000000); /* wait 10 sec and try the lock again */
6890 continue;
6891 }
6892
6893 assert( nTries==3 );
6894 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6895 rc = SQLITE_OK;
6896 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006897 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006898 }
6899 if( !rc ){
6900 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6901 }
6902 }
6903 }
6904 } while( rc==SQLITE_BUSY && nTries<3 );
6905
6906 return rc;
6907}
6908
6909/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006910** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6911** lockPath means that the lockPath in the conch file will be used if the
6912** host IDs match, or a new lock path will be generated automatically
6913** and written to the conch file.
6914*/
6915static int proxyTakeConch(unixFile *pFile){
6916 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6917
drh7ed97b92010-01-20 13:07:21 +00006918 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006919 return SQLITE_OK;
6920 }else{
6921 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006922 uuid_t myHostID;
6923 int pError = 0;
6924 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006925 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006926 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006927 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006928 int createConch = 0;
6929 int hostIdMatch = 0;
6930 int readLen = 0;
6931 int tryOldLockPath = 0;
6932 int forceNewLockPath = 0;
6933
drh308c2a52010-05-14 11:30:18 +00006934 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006935 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006936 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006937
drh7ed97b92010-01-20 13:07:21 +00006938 rc = proxyGetHostID(myHostID, &pError);
6939 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006940 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006941 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006942 }
drh7ed97b92010-01-20 13:07:21 +00006943 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006944 if( rc!=SQLITE_OK ){
6945 goto end_takeconch;
6946 }
drh7ed97b92010-01-20 13:07:21 +00006947 /* read the existing conch file */
6948 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6949 if( readLen<0 ){
6950 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006951 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006952 rc = SQLITE_IOERR_READ;
6953 goto end_takeconch;
6954 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6955 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6956 /* a short read or version format mismatch means we need to create a new
6957 ** conch file.
6958 */
6959 createConch = 1;
6960 }
6961 /* if the host id matches and the lock path already exists in the conch
6962 ** we'll try to use the path there, if we can't open that path, we'll
6963 ** retry with a new auto-generated path
6964 */
6965 do { /* in case we need to try again for an :auto: named lock file */
6966
6967 if( !createConch && !forceNewLockPath ){
6968 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6969 PROXY_HOSTIDLEN);
6970 /* if the conch has data compare the contents */
6971 if( !pCtx->lockProxyPath ){
6972 /* for auto-named local lock file, just check the host ID and we'll
6973 ** use the local lock file path that's already in there
6974 */
6975 if( hostIdMatch ){
6976 size_t pathLen = (readLen - PROXY_PATHINDEX);
6977
6978 if( pathLen>=MAXPATHLEN ){
6979 pathLen=MAXPATHLEN-1;
6980 }
6981 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6982 lockPath[pathLen] = 0;
6983 tempLockPath = lockPath;
6984 tryOldLockPath = 1;
6985 /* create a copy of the lock path if the conch is taken */
6986 goto end_takeconch;
6987 }
6988 }else if( hostIdMatch
6989 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6990 readLen-PROXY_PATHINDEX)
6991 ){
6992 /* conch host and lock path match */
6993 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006994 }
drh7ed97b92010-01-20 13:07:21 +00006995 }
6996
6997 /* if the conch isn't writable and doesn't match, we can't take it */
6998 if( (conchFile->openFlags&O_RDWR) == 0 ){
6999 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007000 goto end_takeconch;
7001 }
drh7ed97b92010-01-20 13:07:21 +00007002
7003 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007004 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007005 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7006 tempLockPath = lockPath;
7007 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007008 }
drh7ed97b92010-01-20 13:07:21 +00007009
7010 /* update conch with host and path (this will fail if other process
7011 ** has a shared lock already), if the host id matches, use the big
7012 ** stick.
drh715ff302008-12-03 22:32:44 +00007013 */
drh7ed97b92010-01-20 13:07:21 +00007014 futimes(conchFile->h, NULL);
7015 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007016 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007017 /* We are trying for an exclusive lock but another thread in this
7018 ** same process is still holding a shared lock. */
7019 rc = SQLITE_BUSY;
7020 } else {
7021 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007022 }
drh715ff302008-12-03 22:32:44 +00007023 }else{
drh4bf66fd2015-02-19 02:43:02 +00007024 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007025 }
drh7ed97b92010-01-20 13:07:21 +00007026 if( rc==SQLITE_OK ){
7027 char writeBuffer[PROXY_MAXCONCHLEN];
7028 int writeSize = 0;
7029
7030 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7031 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7032 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007033 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7034 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007035 }else{
7036 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7037 }
7038 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007039 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007040 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007041 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007042 /* If we created a new conch file (not just updated the contents of a
7043 ** valid conch file), try to match the permissions of the database
7044 */
7045 if( rc==SQLITE_OK && createConch ){
7046 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007047 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007048 if( err==0 ){
7049 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7050 S_IROTH|S_IWOTH);
7051 /* try to match the database file R/W permissions, ignore failure */
7052#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007053 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007054#else
drhff812312011-02-23 13:33:46 +00007055 do{
drhe562be52011-03-02 18:01:10 +00007056 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007057 }while( rc==(-1) && errno==EINTR );
7058 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007059 int code = errno;
7060 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7061 cmode, code, strerror(code));
7062 } else {
7063 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7064 }
7065 }else{
7066 int code = errno;
7067 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7068 err, code, strerror(code));
7069#endif
7070 }
drh715ff302008-12-03 22:32:44 +00007071 }
7072 }
drh7ed97b92010-01-20 13:07:21 +00007073 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7074
7075 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007076 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007077 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007078 int fd;
drh7ed97b92010-01-20 13:07:21 +00007079 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007080 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007081 }
7082 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007083 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007084 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007085 if( fd>=0 ){
7086 pFile->h = fd;
7087 }else{
drh9978c972010-02-23 17:36:32 +00007088 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007089 during locking */
7090 }
7091 }
7092 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7093 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7094 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7095 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7096 /* we couldn't create the proxy lock file with the old lock file path
7097 ** so try again via auto-naming
7098 */
7099 forceNewLockPath = 1;
7100 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007101 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007102 }
7103 }
7104 if( rc==SQLITE_OK ){
7105 /* Need to make a copy of path if we extracted the value
7106 ** from the conch file or the path was allocated on the stack
7107 */
7108 if( tempLockPath ){
7109 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7110 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007111 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007112 }
7113 }
7114 }
7115 if( rc==SQLITE_OK ){
7116 pCtx->conchHeld = 1;
7117
7118 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7119 afpLockingContext *afpCtx;
7120 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7121 afpCtx->dbPath = pCtx->lockProxyPath;
7122 }
7123 } else {
7124 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7125 }
drh308c2a52010-05-14 11:30:18 +00007126 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7127 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007128 return rc;
drh308c2a52010-05-14 11:30:18 +00007129 } while (1); /* in case we need to retry the :auto: lock file -
7130 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007131 }
7132}
7133
7134/*
7135** If pFile holds a lock on a conch file, then release that lock.
7136*/
7137static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007138 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007139 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7140 unixFile *conchFile; /* Name of the conch file */
7141
7142 pCtx = (proxyLockingContext *)pFile->lockingContext;
7143 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007144 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007145 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007146 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007147 if( pCtx->conchHeld>0 ){
7148 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7149 }
drh715ff302008-12-03 22:32:44 +00007150 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007151 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7152 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007153 return rc;
7154}
7155
7156/*
7157** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007158** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007159** Make *pConchPath point to the new name. Return SQLITE_OK on success
7160** or SQLITE_NOMEM if unable to obtain memory.
7161**
7162** The caller is responsible for ensuring that the allocated memory
7163** space is eventually freed.
7164**
7165** *pConchPath is set to NULL if a memory allocation error occurs.
7166*/
7167static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7168 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007169 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007170 char *conchPath; /* buffer in which to construct conch name */
7171
7172 /* Allocate space for the conch filename and initialize the name to
7173 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007174 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007175 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007176 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007177 }
7178 memcpy(conchPath, dbPath, len+1);
7179
7180 /* now insert a "." before the last / character */
7181 for( i=(len-1); i>=0; i-- ){
7182 if( conchPath[i]=='/' ){
7183 i++;
7184 break;
7185 }
7186 }
7187 conchPath[i]='.';
7188 while ( i<len ){
7189 conchPath[i+1]=dbPath[i];
7190 i++;
7191 }
7192
7193 /* append the "-conch" suffix to the file */
7194 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007195 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007196
7197 return SQLITE_OK;
7198}
7199
7200
7201/* Takes a fully configured proxy locking-style unix file and switches
7202** the local lock file path
7203*/
7204static int switchLockProxyPath(unixFile *pFile, const char *path) {
7205 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7206 char *oldPath = pCtx->lockProxyPath;
7207 int rc = SQLITE_OK;
7208
drh308c2a52010-05-14 11:30:18 +00007209 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007210 return SQLITE_BUSY;
7211 }
7212
7213 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7214 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7215 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7216 return SQLITE_OK;
7217 }else{
7218 unixFile *lockProxy = pCtx->lockProxy;
7219 pCtx->lockProxy=NULL;
7220 pCtx->conchHeld = 0;
7221 if( lockProxy!=NULL ){
7222 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7223 if( rc ) return rc;
7224 sqlite3_free(lockProxy);
7225 }
7226 sqlite3_free(oldPath);
7227 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7228 }
7229
7230 return rc;
7231}
7232
7233/*
7234** pFile is a file that has been opened by a prior xOpen call. dbPath
7235** is a string buffer at least MAXPATHLEN+1 characters in size.
7236**
7237** This routine find the filename associated with pFile and writes it
7238** int dbPath.
7239*/
7240static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007241#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007242 if( pFile->pMethod == &afpIoMethods ){
7243 /* afp style keeps a reference to the db path in the filePath field
7244 ** of the struct */
drhea678832008-12-10 19:26:22 +00007245 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007246 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7247 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007248 } else
drh715ff302008-12-03 22:32:44 +00007249#endif
7250 if( pFile->pMethod == &dotlockIoMethods ){
7251 /* dot lock style uses the locking context to store the dot lock
7252 ** file path */
7253 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7254 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7255 }else{
7256 /* all other styles use the locking context to store the db file path */
7257 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007258 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007259 }
7260 return SQLITE_OK;
7261}
7262
7263/*
7264** Takes an already filled in unix file and alters it so all file locking
7265** will be performed on the local proxy lock file. The following fields
7266** are preserved in the locking context so that they can be restored and
7267** the unix structure properly cleaned up at close time:
7268** ->lockingContext
7269** ->pMethod
7270*/
7271static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7272 proxyLockingContext *pCtx;
7273 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7274 char *lockPath=NULL;
7275 int rc = SQLITE_OK;
7276
drh308c2a52010-05-14 11:30:18 +00007277 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007278 return SQLITE_BUSY;
7279 }
7280 proxyGetDbPathForUnixFile(pFile, dbPath);
7281 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7282 lockPath=NULL;
7283 }else{
7284 lockPath=(char *)path;
7285 }
7286
drh308c2a52010-05-14 11:30:18 +00007287 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007288 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007289
drhf3cdcdc2015-04-29 16:50:28 +00007290 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007291 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007292 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007293 }
7294 memset(pCtx, 0, sizeof(*pCtx));
7295
7296 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7297 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007298 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7299 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7300 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7301 ** (c) the file system is read-only, then enable no-locking access.
7302 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7303 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7304 */
7305 struct statfs fsInfo;
7306 struct stat conchInfo;
7307 int goLockless = 0;
7308
drh99ab3b12011-03-02 15:09:07 +00007309 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007310 int err = errno;
7311 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7312 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7313 }
7314 }
7315 if( goLockless ){
7316 pCtx->conchHeld = -1; /* read only FS/ lockless */
7317 rc = SQLITE_OK;
7318 }
7319 }
drh715ff302008-12-03 22:32:44 +00007320 }
7321 if( rc==SQLITE_OK && lockPath ){
7322 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7323 }
7324
7325 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007326 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7327 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007328 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007329 }
7330 }
7331 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007332 /* all memory is allocated, proxys are created and assigned,
7333 ** switch the locking context and pMethod then return.
7334 */
drh715ff302008-12-03 22:32:44 +00007335 pCtx->oldLockingContext = pFile->lockingContext;
7336 pFile->lockingContext = pCtx;
7337 pCtx->pOldMethod = pFile->pMethod;
7338 pFile->pMethod = &proxyIoMethods;
7339 }else{
7340 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007341 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007342 sqlite3_free(pCtx->conchFile);
7343 }
drhd56b1212010-08-11 06:14:15 +00007344 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007345 sqlite3_free(pCtx->conchFilePath);
7346 sqlite3_free(pCtx);
7347 }
drh308c2a52010-05-14 11:30:18 +00007348 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7349 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007350 return rc;
7351}
7352
7353
7354/*
7355** This routine handles sqlite3_file_control() calls that are specific
7356** to proxy locking.
7357*/
7358static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7359 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007360 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007361 unixFile *pFile = (unixFile*)id;
7362 if( pFile->pMethod == &proxyIoMethods ){
7363 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7364 proxyTakeConch(pFile);
7365 if( pCtx->lockProxyPath ){
7366 *(const char **)pArg = pCtx->lockProxyPath;
7367 }else{
7368 *(const char **)pArg = ":auto: (not held)";
7369 }
7370 } else {
7371 *(const char **)pArg = NULL;
7372 }
7373 return SQLITE_OK;
7374 }
drh4bf66fd2015-02-19 02:43:02 +00007375 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007376 unixFile *pFile = (unixFile*)id;
7377 int rc = SQLITE_OK;
7378 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7379 if( pArg==NULL || (const char *)pArg==0 ){
7380 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007381 /* turn off proxy locking - not supported. If support is added for
7382 ** switching proxy locking mode off then it will need to fail if
7383 ** the journal mode is WAL mode.
7384 */
drh715ff302008-12-03 22:32:44 +00007385 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7386 }else{
7387 /* turn off proxy locking - already off - NOOP */
7388 rc = SQLITE_OK;
7389 }
7390 }else{
7391 const char *proxyPath = (const char *)pArg;
7392 if( isProxyStyle ){
7393 proxyLockingContext *pCtx =
7394 (proxyLockingContext*)pFile->lockingContext;
7395 if( !strcmp(pArg, ":auto:")
7396 || (pCtx->lockProxyPath &&
7397 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7398 ){
7399 rc = SQLITE_OK;
7400 }else{
7401 rc = switchLockProxyPath(pFile, proxyPath);
7402 }
7403 }else{
7404 /* turn on proxy file locking */
7405 rc = proxyTransformUnixFile(pFile, proxyPath);
7406 }
7407 }
7408 return rc;
7409 }
7410 default: {
7411 assert( 0 ); /* The call assures that only valid opcodes are sent */
7412 }
7413 }
7414 /*NOTREACHED*/
7415 return SQLITE_ERROR;
7416}
7417
7418/*
7419** Within this division (the proxying locking implementation) the procedures
7420** above this point are all utilities. The lock-related methods of the
7421** proxy-locking sqlite3_io_method object follow.
7422*/
7423
7424
7425/*
7426** This routine checks if there is a RESERVED lock held on the specified
7427** file by this or any other process. If such a lock is held, set *pResOut
7428** to a non-zero value otherwise *pResOut is set to zero. The return value
7429** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7430*/
7431static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7432 unixFile *pFile = (unixFile*)id;
7433 int rc = proxyTakeConch(pFile);
7434 if( rc==SQLITE_OK ){
7435 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007436 if( pCtx->conchHeld>0 ){
7437 unixFile *proxy = pCtx->lockProxy;
7438 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7439 }else{ /* conchHeld < 0 is lockless */
7440 pResOut=0;
7441 }
drh715ff302008-12-03 22:32:44 +00007442 }
7443 return rc;
7444}
7445
7446/*
drh308c2a52010-05-14 11:30:18 +00007447** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007448** of the following:
7449**
7450** (1) SHARED_LOCK
7451** (2) RESERVED_LOCK
7452** (3) PENDING_LOCK
7453** (4) EXCLUSIVE_LOCK
7454**
7455** Sometimes when requesting one lock state, additional lock states
7456** are inserted in between. The locking might fail on one of the later
7457** transitions leaving the lock state different from what it started but
7458** still short of its goal. The following chart shows the allowed
7459** transitions and the inserted intermediate states:
7460**
7461** UNLOCKED -> SHARED
7462** SHARED -> RESERVED
7463** SHARED -> (PENDING) -> EXCLUSIVE
7464** RESERVED -> (PENDING) -> EXCLUSIVE
7465** PENDING -> EXCLUSIVE
7466**
7467** This routine will only increase a lock. Use the sqlite3OsUnlock()
7468** routine to lower a locking level.
7469*/
drh308c2a52010-05-14 11:30:18 +00007470static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007471 unixFile *pFile = (unixFile*)id;
7472 int rc = proxyTakeConch(pFile);
7473 if( rc==SQLITE_OK ){
7474 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007475 if( pCtx->conchHeld>0 ){
7476 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007477 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7478 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007479 }else{
7480 /* conchHeld < 0 is lockless */
7481 }
drh715ff302008-12-03 22:32:44 +00007482 }
7483 return rc;
7484}
7485
7486
7487/*
drh308c2a52010-05-14 11:30:18 +00007488** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007489** must be either NO_LOCK or SHARED_LOCK.
7490**
7491** If the locking level of the file descriptor is already at or below
7492** the requested locking level, this routine is a no-op.
7493*/
drh308c2a52010-05-14 11:30:18 +00007494static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007495 unixFile *pFile = (unixFile*)id;
7496 int rc = proxyTakeConch(pFile);
7497 if( rc==SQLITE_OK ){
7498 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007499 if( pCtx->conchHeld>0 ){
7500 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007501 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7502 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007503 }else{
7504 /* conchHeld < 0 is lockless */
7505 }
drh715ff302008-12-03 22:32:44 +00007506 }
7507 return rc;
7508}
7509
7510/*
7511** Close a file that uses proxy locks.
7512*/
7513static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007514 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007515 unixFile *pFile = (unixFile*)id;
7516 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7517 unixFile *lockProxy = pCtx->lockProxy;
7518 unixFile *conchFile = pCtx->conchFile;
7519 int rc = SQLITE_OK;
7520
7521 if( lockProxy ){
7522 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7523 if( rc ) return rc;
7524 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7525 if( rc ) return rc;
7526 sqlite3_free(lockProxy);
7527 pCtx->lockProxy = 0;
7528 }
7529 if( conchFile ){
7530 if( pCtx->conchHeld ){
7531 rc = proxyReleaseConch(pFile);
7532 if( rc ) return rc;
7533 }
7534 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7535 if( rc ) return rc;
7536 sqlite3_free(conchFile);
7537 }
drhd56b1212010-08-11 06:14:15 +00007538 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007539 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007540 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007541 /* restore the original locking context and pMethod then close it */
7542 pFile->lockingContext = pCtx->oldLockingContext;
7543 pFile->pMethod = pCtx->pOldMethod;
7544 sqlite3_free(pCtx);
7545 return pFile->pMethod->xClose(id);
7546 }
7547 return SQLITE_OK;
7548}
7549
7550
7551
drhd2cb50b2009-01-09 21:41:17 +00007552#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007553/*
7554** The proxy locking style is intended for use with AFP filesystems.
7555** And since AFP is only supported on MacOSX, the proxy locking is also
7556** restricted to MacOSX.
7557**
7558**
7559******************* End of the proxy lock implementation **********************
7560******************************************************************************/
7561
drh734c9862008-11-28 15:37:20 +00007562/*
danielk1977e339d652008-06-28 11:23:00 +00007563** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007564**
7565** This routine registers all VFS implementations for unix-like operating
7566** systems. This routine, and the sqlite3_os_end() routine that follows,
7567** should be the only routines in this file that are visible from other
7568** files.
drh6b9d6dd2008-12-03 19:34:47 +00007569**
7570** This routine is called once during SQLite initialization and by a
7571** single thread. The memory allocation and mutex subsystems have not
7572** necessarily been initialized when this routine is called, and so they
7573** should not be used.
drh153c62c2007-08-24 03:51:33 +00007574*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007575int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007576 /*
7577 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007578 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7579 ** to the "finder" function. (pAppData is a pointer to a pointer because
7580 ** silly C90 rules prohibit a void* from being cast to a function pointer
7581 ** and so we have to go through the intermediate pointer to avoid problems
7582 ** when compiling with -pedantic-errors on GCC.)
7583 **
7584 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007585 ** finder-function. The finder-function returns a pointer to the
7586 ** sqlite_io_methods object that implements the desired locking
7587 ** behaviors. See the division above that contains the IOMETHODS
7588 ** macro for addition information on finder-functions.
7589 **
7590 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7591 ** object. But the "autolockIoFinder" available on MacOSX does a little
7592 ** more than that; it looks at the filesystem type that hosts the
7593 ** database file and tries to choose an locking method appropriate for
7594 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007595 */
drh7708e972008-11-29 00:56:52 +00007596 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007597 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007598 sizeof(unixFile), /* szOsFile */ \
7599 MAX_PATHNAME, /* mxPathname */ \
7600 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007601 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007602 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007603 unixOpen, /* xOpen */ \
7604 unixDelete, /* xDelete */ \
7605 unixAccess, /* xAccess */ \
7606 unixFullPathname, /* xFullPathname */ \
7607 unixDlOpen, /* xDlOpen */ \
7608 unixDlError, /* xDlError */ \
7609 unixDlSym, /* xDlSym */ \
7610 unixDlClose, /* xDlClose */ \
7611 unixRandomness, /* xRandomness */ \
7612 unixSleep, /* xSleep */ \
7613 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007614 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007615 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007616 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007617 unixGetSystemCall, /* xGetSystemCall */ \
7618 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007619 }
7620
drh6b9d6dd2008-12-03 19:34:47 +00007621 /*
7622 ** All default VFSes for unix are contained in the following array.
7623 **
7624 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7625 ** by the SQLite core when the VFS is registered. So the following
7626 ** array cannot be const.
7627 */
danielk1977e339d652008-06-28 11:23:00 +00007628 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007629#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007630 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007631#elif OS_VXWORKS
7632 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007633#else
7634 UNIXVFS("unix", posixIoFinder ),
7635#endif
7636 UNIXVFS("unix-none", nolockIoFinder ),
7637 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007638 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007639#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007640 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007641#endif
drhe89b2912015-03-03 20:42:01 +00007642#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007643 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007644#endif
drhe89b2912015-03-03 20:42:01 +00007645#if SQLITE_ENABLE_LOCKING_STYLE
7646 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007647#endif
drhd2cb50b2009-01-09 21:41:17 +00007648#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007649 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007650 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007651 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007652#endif
drh153c62c2007-08-24 03:51:33 +00007653 };
drh6b9d6dd2008-12-03 19:34:47 +00007654 unsigned int i; /* Loop counter */
7655
drh2aa5a002011-04-13 13:42:25 +00007656 /* Double-check that the aSyscall[] array has been constructed
7657 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007658 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007659
drh6b9d6dd2008-12-03 19:34:47 +00007660 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007661 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007662 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007663 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007664 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007665}
danielk1977e339d652008-06-28 11:23:00 +00007666
7667/*
drh6b9d6dd2008-12-03 19:34:47 +00007668** Shutdown the operating system interface.
7669**
7670** Some operating systems might need to do some cleanup in this routine,
7671** to release dynamically allocated objects. But not on unix.
7672** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007673*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007674int sqlite3_os_end(void){
7675 return SQLITE_OK;
7676}
drhdce8bdb2007-08-16 13:01:44 +00007677
danielk197729bafea2008-06-26 10:41:19 +00007678#endif /* SQLITE_OS_UNIX */