blob: 460b0a9bdca220dbc4a9c9fb806f55b61c03d20a [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
danefe16972017-07-20 19:49:14 +0000330#define F2FS_IOCTL_MAGIC 0xf5
331#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
332#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
333#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
334#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
dan9d709542017-07-21 21:06:24 +0000335#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
336
337#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
danefe16972017-07-20 19:49:14 +0000338
339
dan2ee53412014-09-06 16:49:40 +0000340/*
drh9a3baf12011-04-25 18:01:27 +0000341** Different Unix systems declare open() in different ways. Same use
342** open(const char*,int,mode_t). Others use open(const char*,int,...).
343** The difference is important when using a pointer to the function.
344**
345** The safest way to deal with the problem is to always use this wrapper
346** which always has the same well-defined interface.
347*/
348static int posixOpen(const char *zFile, int flags, int mode){
349 return open(zFile, flags, mode);
350}
351
drh90315a22011-08-10 01:52:12 +0000352/* Forward reference */
353static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000354static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000355
drh9a3baf12011-04-25 18:01:27 +0000356/*
drh99ab3b12011-03-02 15:09:07 +0000357** Many system calls are accessed through pointer-to-functions so that
358** they may be overridden at runtime to facilitate fault injection during
359** testing and sandboxing. The following array holds the names and pointers
360** to all overrideable system calls.
361*/
362static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000363 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000364 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
365 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000366} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000367 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
368#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000369
drh58ad5802011-03-23 22:02:23 +0000370 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osClose ((int(*)(int))aSyscall[1].pCurrent)
372
drh58ad5802011-03-23 22:02:23 +0000373 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000374#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
375
drh58ad5802011-03-23 22:02:23 +0000376 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000377#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
378
drh58ad5802011-03-23 22:02:23 +0000379 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000380#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
381
382/*
383** The DJGPP compiler environment looks mostly like Unix, but it
384** lacks the fcntl() system call. So redefine fcntl() to be something
385** that always succeeds. This means that locking does not occur under
386** DJGPP. But it is DOS - what did you expect?
387*/
388#ifdef __DJGPP__
389 { "fstat", 0, 0 },
390#define osFstat(a,b,c) 0
391#else
drh58ad5802011-03-23 22:02:23 +0000392 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000393#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
394#endif
395
drh58ad5802011-03-23 22:02:23 +0000396 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000397#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
398
drh58ad5802011-03-23 22:02:23 +0000399 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000400#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000401
drh58ad5802011-03-23 22:02:23 +0000402 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000403#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
404
drhe89b2912015-03-03 20:42:01 +0000405#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000406 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000407#else
drh58ad5802011-03-23 22:02:23 +0000408 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000409#endif
410#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
411
412#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000413 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000414#else
drh58ad5802011-03-23 22:02:23 +0000415 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000416#endif
drhf9986d92016-04-18 13:09:55 +0000417#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
drhe562be52011-03-02 18:01:10 +0000418
drh58ad5802011-03-23 22:02:23 +0000419 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000420#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
421
drhe89b2912015-03-03 20:42:01 +0000422#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000423 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000424#else
drh58ad5802011-03-23 22:02:23 +0000425 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000426#endif
427#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
428 aSyscall[12].pCurrent)
429
430#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000431 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000432#else
drh58ad5802011-03-23 22:02:23 +0000433 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000434#endif
drhf9986d92016-04-18 13:09:55 +0000435#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
drhe562be52011-03-02 18:01:10 +0000436 aSyscall[13].pCurrent)
437
drh6226ca22015-11-24 15:06:28 +0000438 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000439#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000440
441#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000442 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000443#else
drh58ad5802011-03-23 22:02:23 +0000444 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000445#endif
dan0fd7d862011-03-29 10:04:23 +0000446#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000447
drh036ac7f2011-08-08 23:18:05 +0000448 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
449#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
450
drh90315a22011-08-10 01:52:12 +0000451 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
452#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
453
drh9ef6bc42011-11-04 02:24:02 +0000454 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
455#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
456
457 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
458#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
459
drhe2258a22016-01-12 00:37:55 +0000460#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000461 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000462#else
463 { "fchown", (sqlite3_syscall_ptr)0, 0 },
464#endif
dand3eaebd2012-02-13 08:50:23 +0000465#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000466
drh6226ca22015-11-24 15:06:28 +0000467 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
468#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
469
dan4dd51442013-08-26 14:30:25 +0000470#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000471 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
472#else
473 { "mmap", (sqlite3_syscall_ptr)0, 0 },
474#endif
drh6226ca22015-11-24 15:06:28 +0000475#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000476
drhe4a08f92016-01-08 19:17:30 +0000477#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000478 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000479#else
drha8299922016-01-08 22:31:00 +0000480 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000481#endif
drh6226ca22015-11-24 15:06:28 +0000482#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000483
drhe4a08f92016-01-08 19:17:30 +0000484#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000485 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
486#else
487 { "mremap", (sqlite3_syscall_ptr)0, 0 },
488#endif
drh6226ca22015-11-24 15:06:28 +0000489#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
490
drh24dbeae2016-01-08 22:18:00 +0000491#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000492 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000493#else
494 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
495#endif
drh6226ca22015-11-24 15:06:28 +0000496#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000497
drhe2258a22016-01-12 00:37:55 +0000498#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000499 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000500#else
501 { "readlink", (sqlite3_syscall_ptr)0, 0 },
502#endif
drh6226ca22015-11-24 15:06:28 +0000503#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000504
danaf1b36b2016-01-25 18:43:05 +0000505#if defined(HAVE_LSTAT)
506 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
507#else
508 { "lstat", (sqlite3_syscall_ptr)0, 0 },
509#endif
dancaf6b152016-01-25 18:05:49 +0000510#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000511
danefe16972017-07-20 19:49:14 +0000512 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
dan9d709542017-07-21 21:06:24 +0000513#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
danefe16972017-07-20 19:49:14 +0000514
drhe562be52011-03-02 18:01:10 +0000515}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000516
drh6226ca22015-11-24 15:06:28 +0000517
518/*
519** On some systems, calls to fchown() will trigger a message in a security
520** log if they come from non-root processes. So avoid calling fchown() if
521** we are not running as root.
522*/
523static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000524#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000525 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000526#else
527 return 0;
drh6226ca22015-11-24 15:06:28 +0000528#endif
529}
530
drh99ab3b12011-03-02 15:09:07 +0000531/*
532** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000533** "unix" VFSes. Return SQLITE_OK opon successfully updating the
534** system call pointer, or SQLITE_NOTFOUND if there is no configurable
535** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000536*/
537static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000538 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
539 const char *zName, /* Name of system call to override */
540 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000541){
drh58ad5802011-03-23 22:02:23 +0000542 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000543 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000544
545 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000546 if( zName==0 ){
547 /* If no zName is given, restore all system calls to their default
548 ** settings and return NULL
549 */
dan51438a72011-04-02 17:00:47 +0000550 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000551 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
552 if( aSyscall[i].pDefault ){
553 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000554 }
555 }
556 }else{
557 /* If zName is specified, operate on only the one system call
558 ** specified.
559 */
560 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
561 if( strcmp(zName, aSyscall[i].zName)==0 ){
562 if( aSyscall[i].pDefault==0 ){
563 aSyscall[i].pDefault = aSyscall[i].pCurrent;
564 }
drh1df30962011-03-02 19:06:42 +0000565 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000566 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
567 aSyscall[i].pCurrent = pNewFunc;
568 break;
569 }
570 }
571 }
572 return rc;
573}
574
drh1df30962011-03-02 19:06:42 +0000575/*
576** Return the value of a system call. Return NULL if zName is not a
577** recognized system call name. NULL is also returned if the system call
578** is currently undefined.
579*/
drh58ad5802011-03-23 22:02:23 +0000580static sqlite3_syscall_ptr unixGetSystemCall(
581 sqlite3_vfs *pNotUsed,
582 const char *zName
583){
584 unsigned int i;
585
586 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000587 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
588 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
589 }
590 return 0;
591}
592
593/*
594** Return the name of the first system call after zName. If zName==NULL
595** then return the name of the first system call. Return NULL if zName
596** is the last system call or if zName is not the name of a valid
597** system call.
598*/
599static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000600 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000601
602 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000603 if( zName ){
604 for(i=0; i<ArraySize(aSyscall)-1; i++){
605 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000606 }
607 }
dan0fd7d862011-03-29 10:04:23 +0000608 for(i++; i<ArraySize(aSyscall); i++){
609 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000610 }
611 return 0;
612}
613
drhad4f1e52011-03-04 15:43:57 +0000614/*
drh77a3fdc2013-08-30 14:24:12 +0000615** Do not accept any file descriptor less than this value, in order to avoid
616** opening database file using file descriptors that are commonly used for
617** standard input, output, and error.
618*/
619#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
620# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
621#endif
622
623/*
drh8c815d12012-02-13 20:16:37 +0000624** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000625** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000626**
627** If the file creation mode "m" is 0 then set it to the default for
628** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
629** 0644) as modified by the system umask. If m is not 0, then
630** make the file creation mode be exactly m ignoring the umask.
631**
632** The m parameter will be non-zero only when creating -wal, -journal,
633** and -shm files. We want those files to have *exactly* the same
634** permissions as their original database, unadulterated by the umask.
635** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
636** transaction crashes and leaves behind hot journals, then any
637** process that is able to write to the database will also be able to
638** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000639*/
drh8c815d12012-02-13 20:16:37 +0000640static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000641 int fd;
drhe1186ab2013-01-04 20:45:13 +0000642 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000643 while(1){
drh5adc60b2012-04-14 13:25:11 +0000644#if defined(O_CLOEXEC)
645 fd = osOpen(z,f|O_CLOEXEC,m2);
646#else
647 fd = osOpen(z,f,m2);
648#endif
drh5128d002013-08-30 06:20:23 +0000649 if( fd<0 ){
650 if( errno==EINTR ) continue;
651 break;
652 }
drh77a3fdc2013-08-30 14:24:12 +0000653 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000654 osClose(fd);
655 sqlite3_log(SQLITE_WARNING,
656 "attempt to open \"%s\" as file descriptor %d", z, fd);
657 fd = -1;
658 if( osOpen("/dev/null", f, m)<0 ) break;
659 }
drhe1186ab2013-01-04 20:45:13 +0000660 if( fd>=0 ){
661 if( m!=0 ){
662 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000663 if( osFstat(fd, &statbuf)==0
664 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000665 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000666 ){
drhe1186ab2013-01-04 20:45:13 +0000667 osFchmod(fd, m);
668 }
669 }
drh5adc60b2012-04-14 13:25:11 +0000670#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000671 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000672#endif
drhe1186ab2013-01-04 20:45:13 +0000673 }
drh5adc60b2012-04-14 13:25:11 +0000674 return fd;
drhad4f1e52011-03-04 15:43:57 +0000675}
danielk197713adf8a2004-06-03 16:08:41 +0000676
drh107886a2008-11-21 22:21:50 +0000677/*
dan9359c7b2009-08-21 08:29:10 +0000678** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000679** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000680** vxworksFileId objects used by this file, all of which may be
681** shared by multiple threads.
682**
683** Function unixMutexHeld() is used to assert() that the global mutex
684** is held when required. This function is only used as part of assert()
685** statements. e.g.
686**
687** unixEnterMutex()
688** assert( unixMutexHeld() );
689** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000690*/
691static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000692 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000693}
694static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000695 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000696}
dan9359c7b2009-08-21 08:29:10 +0000697#ifdef SQLITE_DEBUG
698static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000699 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000700}
701#endif
drh107886a2008-11-21 22:21:50 +0000702
drh734c9862008-11-28 15:37:20 +0000703
mistachkinfb383e92015-04-16 03:24:38 +0000704#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000705/*
706** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000707** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000708** integer lock-type.
709*/
drh308c2a52010-05-14 11:30:18 +0000710static const char *azFileLock(int eFileLock){
711 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000712 case NO_LOCK: return "NONE";
713 case SHARED_LOCK: return "SHARED";
714 case RESERVED_LOCK: return "RESERVED";
715 case PENDING_LOCK: return "PENDING";
716 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000717 }
718 return "ERROR";
719}
720#endif
721
722#ifdef SQLITE_LOCK_TRACE
723/*
724** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000725**
drh734c9862008-11-28 15:37:20 +0000726** This routine is used for troubleshooting locks on multithreaded
727** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
728** command-line option on the compiler. This code is normally
729** turned off.
730*/
731static int lockTrace(int fd, int op, struct flock *p){
732 char *zOpName, *zType;
733 int s;
734 int savedErrno;
735 if( op==F_GETLK ){
736 zOpName = "GETLK";
737 }else if( op==F_SETLK ){
738 zOpName = "SETLK";
739 }else{
drh99ab3b12011-03-02 15:09:07 +0000740 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000741 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
742 return s;
743 }
744 if( p->l_type==F_RDLCK ){
745 zType = "RDLCK";
746 }else if( p->l_type==F_WRLCK ){
747 zType = "WRLCK";
748 }else if( p->l_type==F_UNLCK ){
749 zType = "UNLCK";
750 }else{
751 assert( 0 );
752 }
753 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000754 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000755 savedErrno = errno;
756 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
757 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
758 (int)p->l_pid, s);
759 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
760 struct flock l2;
761 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000762 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000763 if( l2.l_type==F_RDLCK ){
764 zType = "RDLCK";
765 }else if( l2.l_type==F_WRLCK ){
766 zType = "WRLCK";
767 }else if( l2.l_type==F_UNLCK ){
768 zType = "UNLCK";
769 }else{
770 assert( 0 );
771 }
772 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
773 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
774 }
775 errno = savedErrno;
776 return s;
777}
drh99ab3b12011-03-02 15:09:07 +0000778#undef osFcntl
779#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000780#endif /* SQLITE_LOCK_TRACE */
781
drhff812312011-02-23 13:33:46 +0000782/*
783** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000784**
drhe6d41732015-02-21 00:49:00 +0000785** All calls to ftruncate() within this file should be made through
786** this wrapper. On the Android platform, bypassing the logic below
787** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000788*/
drhff812312011-02-23 13:33:46 +0000789static int robust_ftruncate(int h, sqlite3_int64 sz){
790 int rc;
dan2ee53412014-09-06 16:49:40 +0000791#ifdef __ANDROID__
792 /* On Android, ftruncate() always uses 32-bit offsets, even if
793 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000794 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000795 ** such attempts. */
796 if( sz>(sqlite3_int64)0x7FFFFFFF ){
797 rc = SQLITE_OK;
798 }else
799#endif
drh99ab3b12011-03-02 15:09:07 +0000800 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000801 return rc;
802}
drh734c9862008-11-28 15:37:20 +0000803
804/*
805** This routine translates a standard POSIX errno code into something
806** useful to the clients of the sqlite3 functions. Specifically, it is
807** intended to translate a variety of "try again" errors into SQLITE_BUSY
808** and a variety of "please close the file descriptor NOW" errors into
809** SQLITE_IOERR
810**
811** Errors during initialization of locks, or file system support for locks,
812** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
813*/
814static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000815 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
816 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
817 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
818 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000819 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000820 case EACCES:
drh734c9862008-11-28 15:37:20 +0000821 case EAGAIN:
822 case ETIMEDOUT:
823 case EBUSY:
824 case EINTR:
825 case ENOLCK:
826 /* random NFS retry error, unless during file system support
827 * introspection, in which it actually means what it says */
828 return SQLITE_BUSY;
829
drh734c9862008-11-28 15:37:20 +0000830 case EPERM:
831 return SQLITE_PERM;
832
drh734c9862008-11-28 15:37:20 +0000833 default:
834 return sqliteIOErr;
835 }
836}
837
838
drh734c9862008-11-28 15:37:20 +0000839/******************************************************************************
840****************** Begin Unique File ID Utility Used By VxWorks ***************
841**
842** On most versions of unix, we can get a unique ID for a file by concatenating
843** the device number and the inode number. But this does not work on VxWorks.
844** On VxWorks, a unique file id must be based on the canonical filename.
845**
846** A pointer to an instance of the following structure can be used as a
847** unique file ID in VxWorks. Each instance of this structure contains
848** a copy of the canonical filename. There is also a reference count.
849** The structure is reclaimed when the number of pointers to it drops to
850** zero.
851**
852** There are never very many files open at one time and lookups are not
853** a performance-critical path, so it is sufficient to put these
854** structures on a linked list.
855*/
856struct vxworksFileId {
857 struct vxworksFileId *pNext; /* Next in a list of them all */
858 int nRef; /* Number of references to this one */
859 int nName; /* Length of the zCanonicalName[] string */
860 char *zCanonicalName; /* Canonical filename */
861};
862
863#if OS_VXWORKS
864/*
drh9b35ea62008-11-29 02:20:26 +0000865** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000866** variable:
867*/
868static struct vxworksFileId *vxworksFileList = 0;
869
870/*
871** Simplify a filename into its canonical form
872** by making the following changes:
873**
874** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000875** * convert /./ into just /
876** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000877**
878** Changes are made in-place. Return the new name length.
879**
880** The original filename is in z[0..n-1]. Return the number of
881** characters in the simplified name.
882*/
883static int vxworksSimplifyName(char *z, int n){
884 int i, j;
885 while( n>1 && z[n-1]=='/' ){ n--; }
886 for(i=j=0; i<n; i++){
887 if( z[i]=='/' ){
888 if( z[i+1]=='/' ) continue;
889 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
890 i += 1;
891 continue;
892 }
893 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
894 while( j>0 && z[j-1]!='/' ){ j--; }
895 if( j>0 ){ j--; }
896 i += 2;
897 continue;
898 }
899 }
900 z[j++] = z[i];
901 }
902 z[j] = 0;
903 return j;
904}
905
906/*
907** Find a unique file ID for the given absolute pathname. Return
908** a pointer to the vxworksFileId object. This pointer is the unique
909** file ID.
910**
911** The nRef field of the vxworksFileId object is incremented before
912** the object is returned. A new vxworksFileId object is created
913** and added to the global list if necessary.
914**
915** If a memory allocation error occurs, return NULL.
916*/
917static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
918 struct vxworksFileId *pNew; /* search key and new file ID */
919 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
920 int n; /* Length of zAbsoluteName string */
921
922 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000923 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000924 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000925 if( pNew==0 ) return 0;
926 pNew->zCanonicalName = (char*)&pNew[1];
927 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
928 n = vxworksSimplifyName(pNew->zCanonicalName, n);
929
930 /* Search for an existing entry that matching the canonical name.
931 ** If found, increment the reference count and return a pointer to
932 ** the existing file ID.
933 */
934 unixEnterMutex();
935 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
936 if( pCandidate->nName==n
937 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
938 ){
939 sqlite3_free(pNew);
940 pCandidate->nRef++;
941 unixLeaveMutex();
942 return pCandidate;
943 }
944 }
945
946 /* No match was found. We will make a new file ID */
947 pNew->nRef = 1;
948 pNew->nName = n;
949 pNew->pNext = vxworksFileList;
950 vxworksFileList = pNew;
951 unixLeaveMutex();
952 return pNew;
953}
954
955/*
956** Decrement the reference count on a vxworksFileId object. Free
957** the object when the reference count reaches zero.
958*/
959static void vxworksReleaseFileId(struct vxworksFileId *pId){
960 unixEnterMutex();
961 assert( pId->nRef>0 );
962 pId->nRef--;
963 if( pId->nRef==0 ){
964 struct vxworksFileId **pp;
965 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
966 assert( *pp==pId );
967 *pp = pId->pNext;
968 sqlite3_free(pId);
969 }
970 unixLeaveMutex();
971}
972#endif /* OS_VXWORKS */
973/*************** End of Unique File ID Utility Used By VxWorks ****************
974******************************************************************************/
975
976
977/******************************************************************************
978*************************** Posix Advisory Locking ****************************
979**
drh9b35ea62008-11-29 02:20:26 +0000980** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000981** section 6.5.2.2 lines 483 through 490 specify that when a process
982** sets or clears a lock, that operation overrides any prior locks set
983** by the same process. It does not explicitly say so, but this implies
984** that it overrides locks set by the same process using a different
985** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000986**
987** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000988** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
989**
990** Suppose ./file1 and ./file2 are really the same file (because
991** one is a hard or symbolic link to the other) then if you set
992** an exclusive lock on fd1, then try to get an exclusive lock
993** on fd2, it works. I would have expected the second lock to
994** fail since there was already a lock on the file due to fd1.
995** But not so. Since both locks came from the same process, the
996** second overrides the first, even though they were on different
997** file descriptors opened on different file names.
998**
drh734c9862008-11-28 15:37:20 +0000999** This means that we cannot use POSIX locks to synchronize file access
1000** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001001** to synchronize access for threads in separate processes, but not
1002** threads within the same process.
1003**
1004** To work around the problem, SQLite has to manage file locks internally
1005** on its own. Whenever a new database is opened, we have to find the
1006** specific inode of the database file (the inode is determined by the
1007** st_dev and st_ino fields of the stat structure that fstat() fills in)
1008** and check for locks already existing on that inode. When locks are
1009** created or removed, we have to look at our own internal record of the
1010** locks to see if another thread has previously set a lock on that same
1011** inode.
1012**
drh9b35ea62008-11-29 02:20:26 +00001013** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1014** For VxWorks, we have to use the alternative unique ID system based on
1015** canonical filename and implemented in the previous division.)
1016**
danielk1977ad94b582007-08-20 06:44:22 +00001017** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001018** descriptor. It is now a structure that holds the integer file
1019** descriptor and a pointer to a structure that describes the internal
1020** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001021** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001022** point to the same locking structure. The locking structure keeps
1023** a reference count (so we will know when to delete it) and a "cnt"
1024** field that tells us its internal lock status. cnt==0 means the
1025** file is unlocked. cnt==-1 means the file has an exclusive lock.
1026** cnt>0 means there are cnt shared locks on the file.
1027**
1028** Any attempt to lock or unlock a file first checks the locking
1029** structure. The fcntl() system call is only invoked to set a
1030** POSIX lock if the internal lock structure transitions between
1031** a locked and an unlocked state.
1032**
drh734c9862008-11-28 15:37:20 +00001033** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001034**
1035** If you close a file descriptor that points to a file that has locks,
1036** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001037** released. To work around this problem, each unixInodeInfo object
1038** maintains a count of the number of pending locks on tha inode.
1039** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001040** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001041** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001042** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001043** be closed and that list is walked (and cleared) when the last lock
1044** clears.
1045**
drh9b35ea62008-11-29 02:20:26 +00001046** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001047**
drh9b35ea62008-11-29 02:20:26 +00001048** Many older versions of linux use the LinuxThreads library which is
1049** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001050** A cannot be modified or overridden by a different thread B.
1051** Only thread A can modify the lock. Locking behavior is correct
1052** if the appliation uses the newer Native Posix Thread Library (NPTL)
1053** on linux - with NPTL a lock created by thread A can override locks
1054** in thread B. But there is no way to know at compile-time which
1055** threading library is being used. So there is no way to know at
1056** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001057** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001058** current process.
drh5fdae772004-06-29 03:29:00 +00001059**
drh8af6c222010-05-14 12:43:01 +00001060** SQLite used to support LinuxThreads. But support for LinuxThreads
1061** was dropped beginning with version 3.7.0. SQLite will still work with
1062** LinuxThreads provided that (1) there is no more than one connection
1063** per database file in the same process and (2) database connections
1064** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001065*/
1066
1067/*
1068** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001069** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001070*/
1071struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001072 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001073#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001074 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001075#else
drh25ef7f52016-12-05 20:06:45 +00001076 /* We are told that some versions of Android contain a bug that
1077 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1078 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1079 ** To work around this, always allocate 64-bits for the inode number.
1080 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1081 ** but that should not be a big deal. */
1082 /* WAS: ino_t ino; */
1083 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001084#endif
1085};
1086
1087/*
drhbbd42a62004-05-22 17:41:58 +00001088** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001089** inode. Or, on LinuxThreads, there is one of these structures for
1090** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001091**
danielk1977ad94b582007-08-20 06:44:22 +00001092** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001093** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001094** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001095*/
drh8af6c222010-05-14 12:43:01 +00001096struct unixInodeInfo {
1097 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001098 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001099 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1100 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001101 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001102 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1103 int nLock; /* Number of outstanding file locks */
1104 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1105 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1106 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001107#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001108 unsigned long long sharedByte; /* for AFP simulated shared lock */
1109#endif
drh6c7d5c52008-11-21 20:32:33 +00001110#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001111 sem_t *pSem; /* Named POSIX semaphore */
1112 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001113#endif
drhbbd42a62004-05-22 17:41:58 +00001114};
1115
drhda0e7682008-07-30 15:27:54 +00001116/*
drh8af6c222010-05-14 12:43:01 +00001117** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001118*/
drhd91c68f2010-05-14 14:52:25 +00001119static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001120
drh5fdae772004-06-29 03:29:00 +00001121/*
dane18d4952011-02-21 11:46:24 +00001122**
drhaaeaa182015-11-24 15:12:47 +00001123** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001124** unixLogError().
1125**
1126** It is invoked after an error occurs in an OS function and errno has been
1127** set. It logs a message using sqlite3_log() containing the current value of
1128** errno and, if possible, the human-readable equivalent from strerror() or
1129** strerror_r().
1130**
1131** The first argument passed to the macro should be the error code that
1132** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1133** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001134** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001135** if any.
1136*/
drh0e9365c2011-03-02 02:08:13 +00001137#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1138static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001139 int errcode, /* SQLite error code */
1140 const char *zFunc, /* Name of OS function that failed */
1141 const char *zPath, /* File path associated with error */
1142 int iLine /* Source line number where error occurred */
1143){
1144 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001145 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001146
1147 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1148 ** the strerror() function to obtain the human-readable error message
1149 ** equivalent to errno. Otherwise, use strerror_r().
1150 */
1151#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1152 char aErr[80];
1153 memset(aErr, 0, sizeof(aErr));
1154 zErr = aErr;
1155
1156 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001157 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001158 ** returns a pointer to a buffer containing the error message. That pointer
1159 ** may point to aErr[], or it may point to some static storage somewhere.
1160 ** Otherwise, assume that the system provides the POSIX version of
1161 ** strerror_r(), which always writes an error message into aErr[].
1162 **
1163 ** If the code incorrectly assumes that it is the POSIX version that is
1164 ** available, the error message will often be an empty string. Not a
1165 ** huge problem. Incorrectly concluding that the GNU version is available
1166 ** could lead to a segfault though.
1167 */
1168#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1169 zErr =
1170# endif
drh0e9365c2011-03-02 02:08:13 +00001171 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001172
1173#elif SQLITE_THREADSAFE
1174 /* This is a threadsafe build, but strerror_r() is not available. */
1175 zErr = "";
1176#else
1177 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001178 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001179#endif
1180
drh0e9365c2011-03-02 02:08:13 +00001181 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001182 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001183 "os_unix.c:%d: (%d) %s(%s) - %s",
1184 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001185 );
1186
1187 return errcode;
1188}
1189
drh0e9365c2011-03-02 02:08:13 +00001190/*
1191** Close a file descriptor.
1192**
1193** We assume that close() almost always works, since it is only in a
1194** very sick application or on a very sick platform that it might fail.
1195** If it does fail, simply leak the file descriptor, but do log the
1196** error.
1197**
1198** Note that it is not safe to retry close() after EINTR since the
1199** file descriptor might have already been reused by another thread.
1200** So we don't even try to recover from an EINTR. Just log the error
1201** and move on.
1202*/
1203static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001204 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001205 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1206 pFile ? pFile->zPath : 0, lineno);
1207 }
1208}
dane18d4952011-02-21 11:46:24 +00001209
1210/*
drhe6d41732015-02-21 00:49:00 +00001211** Set the pFile->lastErrno. Do this in a subroutine as that provides
1212** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001213*/
1214static void storeLastErrno(unixFile *pFile, int error){
1215 pFile->lastErrno = error;
1216}
1217
1218/*
danb0ac3e32010-06-16 10:55:42 +00001219** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001220*/
drh0e9365c2011-03-02 02:08:13 +00001221static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001222 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001223 UnixUnusedFd *p;
1224 UnixUnusedFd *pNext;
1225 for(p=pInode->pUnused; p; p=pNext){
1226 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001227 robust_close(pFile, p->fd, __LINE__);
1228 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001229 }
drh0e9365c2011-03-02 02:08:13 +00001230 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001231}
1232
1233/*
drh8af6c222010-05-14 12:43:01 +00001234** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001235**
1236** The mutex entered using the unixEnterMutex() function must be held
1237** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001238*/
danb0ac3e32010-06-16 10:55:42 +00001239static void releaseInodeInfo(unixFile *pFile){
1240 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001241 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001242 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001243 pInode->nRef--;
1244 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001245 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001246 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001247 if( pInode->pPrev ){
1248 assert( pInode->pPrev->pNext==pInode );
1249 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001250 }else{
drh8af6c222010-05-14 12:43:01 +00001251 assert( inodeList==pInode );
1252 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001253 }
drh8af6c222010-05-14 12:43:01 +00001254 if( pInode->pNext ){
1255 assert( pInode->pNext->pPrev==pInode );
1256 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001257 }
drh8af6c222010-05-14 12:43:01 +00001258 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001259 }
drhbbd42a62004-05-22 17:41:58 +00001260 }
1261}
1262
1263/*
drh8af6c222010-05-14 12:43:01 +00001264** Given a file descriptor, locate the unixInodeInfo object that
1265** describes that file descriptor. Create a new one if necessary. The
1266** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001267**
dan9359c7b2009-08-21 08:29:10 +00001268** The mutex entered using the unixEnterMutex() function must be held
1269** when this function is called.
1270**
drh6c7d5c52008-11-21 20:32:33 +00001271** Return an appropriate error code.
1272*/
drh8af6c222010-05-14 12:43:01 +00001273static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001274 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001275 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001276){
1277 int rc; /* System call return code */
1278 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001279 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1280 struct stat statbuf; /* Low-level file information */
1281 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001282
dan9359c7b2009-08-21 08:29:10 +00001283 assert( unixMutexHeld() );
1284
drh6c7d5c52008-11-21 20:32:33 +00001285 /* Get low-level information about the file that we can used to
1286 ** create a unique name for the file.
1287 */
1288 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001289 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001290 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001291 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001292#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001293 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1294#endif
1295 return SQLITE_IOERR;
1296 }
1297
drheb0d74f2009-02-03 15:27:02 +00001298#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001299 /* On OS X on an msdos filesystem, the inode number is reported
1300 ** incorrectly for zero-size files. See ticket #3260. To work
1301 ** around this problem (we consider it a bug in OS X, not SQLite)
1302 ** we always increase the file size to 1 by writing a single byte
1303 ** prior to accessing the inode number. The one byte written is
1304 ** an ASCII 'S' character which also happens to be the first byte
1305 ** in the header of every SQLite database. In this way, if there
1306 ** is a race condition such that another thread has already populated
1307 ** the first page of the database, no damage is done.
1308 */
drh7ed97b92010-01-20 13:07:21 +00001309 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001310 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001311 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001312 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001313 return SQLITE_IOERR;
1314 }
drh99ab3b12011-03-02 15:09:07 +00001315 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001316 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001317 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001318 return SQLITE_IOERR;
1319 }
1320 }
drheb0d74f2009-02-03 15:27:02 +00001321#endif
drh6c7d5c52008-11-21 20:32:33 +00001322
drh8af6c222010-05-14 12:43:01 +00001323 memset(&fileId, 0, sizeof(fileId));
1324 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001325#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001326 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001327#else
drh25ef7f52016-12-05 20:06:45 +00001328 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001329#endif
drh8af6c222010-05-14 12:43:01 +00001330 pInode = inodeList;
1331 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1332 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001333 }
drh8af6c222010-05-14 12:43:01 +00001334 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001335 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001336 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001337 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001338 }
drh8af6c222010-05-14 12:43:01 +00001339 memset(pInode, 0, sizeof(*pInode));
1340 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1341 pInode->nRef = 1;
1342 pInode->pNext = inodeList;
1343 pInode->pPrev = 0;
1344 if( inodeList ) inodeList->pPrev = pInode;
1345 inodeList = pInode;
1346 }else{
1347 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001348 }
drh8af6c222010-05-14 12:43:01 +00001349 *ppInode = pInode;
1350 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001351}
drh6c7d5c52008-11-21 20:32:33 +00001352
drhb959a012013-12-07 12:29:22 +00001353/*
1354** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1355*/
1356static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001357#if OS_VXWORKS
1358 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1359#else
drhb959a012013-12-07 12:29:22 +00001360 struct stat buf;
1361 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001362 (osStat(pFile->zPath, &buf)!=0
1363 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001364#endif
drhb959a012013-12-07 12:29:22 +00001365}
1366
aswift5b1a2562008-08-22 00:22:35 +00001367
1368/*
drhfbc7e882013-04-11 01:16:15 +00001369** Check a unixFile that is a database. Verify the following:
1370**
1371** (1) There is exactly one hard link on the file
1372** (2) The file is not a symbolic link
1373** (3) The file has not been renamed or unlinked
1374**
1375** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1376*/
1377static void verifyDbFile(unixFile *pFile){
1378 struct stat buf;
1379 int rc;
drh86151e82015-12-08 14:37:16 +00001380
1381 /* These verifications occurs for the main database only */
1382 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1383
drhfbc7e882013-04-11 01:16:15 +00001384 rc = osFstat(pFile->h, &buf);
1385 if( rc!=0 ){
1386 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001387 return;
1388 }
drh6369bc32016-03-21 16:06:42 +00001389 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001390 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001391 return;
1392 }
1393 if( buf.st_nlink>1 ){
1394 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001395 return;
1396 }
drhb959a012013-12-07 12:29:22 +00001397 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001398 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001399 return;
1400 }
1401}
1402
1403
1404/*
danielk197713adf8a2004-06-03 16:08:41 +00001405** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001406** file by this or any other process. If such a lock is held, set *pResOut
1407** to a non-zero value otherwise *pResOut is set to zero. The return value
1408** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001409*/
danielk1977861f7452008-06-05 11:39:11 +00001410static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001411 int rc = SQLITE_OK;
1412 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001413 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001414
danielk1977861f7452008-06-05 11:39:11 +00001415 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1416
drh054889e2005-11-30 03:20:31 +00001417 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001418 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001419 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001420
1421 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001422 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001423 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001424 }
1425
drh2ac3ee92004-06-07 16:27:46 +00001426 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001427 */
danielk197709480a92009-02-09 05:32:32 +00001428#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001429 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001430 struct flock lock;
1431 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001432 lock.l_start = RESERVED_BYTE;
1433 lock.l_len = 1;
1434 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001435 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1436 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001437 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001438 } else if( lock.l_type!=F_UNLCK ){
1439 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001440 }
1441 }
danielk197709480a92009-02-09 05:32:32 +00001442#endif
danielk197713adf8a2004-06-03 16:08:41 +00001443
drh6c7d5c52008-11-21 20:32:33 +00001444 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001445 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001446
aswift5b1a2562008-08-22 00:22:35 +00001447 *pResOut = reserved;
1448 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001449}
1450
1451/*
drha7e61d82011-03-12 17:02:57 +00001452** Attempt to set a system-lock on the file pFile. The lock is
1453** described by pLock.
1454**
drh77197112011-03-15 19:08:48 +00001455** If the pFile was opened read/write from unix-excl, then the only lock
1456** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001457** the first time any lock is attempted. All subsequent system locking
1458** operations become no-ops. Locking operations still happen internally,
1459** in order to coordinate access between separate database connections
1460** within this process, but all of that is handled in memory and the
1461** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001462**
1463** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1464** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1465** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001466**
1467** Zero is returned if the call completes successfully, or -1 if a call
1468** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001469*/
1470static int unixFileLock(unixFile *pFile, struct flock *pLock){
1471 int rc;
drh3cb93392011-03-12 18:10:44 +00001472 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001473 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001474 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001475 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001476 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001477 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001478 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001479 lock.l_whence = SEEK_SET;
1480 lock.l_start = SHARED_FIRST;
1481 lock.l_len = SHARED_SIZE;
1482 lock.l_type = F_WRLCK;
1483 rc = osFcntl(pFile->h, F_SETLK, &lock);
1484 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001485 pInode->bProcessLock = 1;
1486 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001487 }else{
1488 rc = 0;
1489 }
1490 }else{
1491 rc = osFcntl(pFile->h, F_SETLK, pLock);
1492 }
1493 return rc;
1494}
1495
1496/*
drh308c2a52010-05-14 11:30:18 +00001497** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001498** of the following:
1499**
drh2ac3ee92004-06-07 16:27:46 +00001500** (1) SHARED_LOCK
1501** (2) RESERVED_LOCK
1502** (3) PENDING_LOCK
1503** (4) EXCLUSIVE_LOCK
1504**
drhb3e04342004-06-08 00:47:47 +00001505** Sometimes when requesting one lock state, additional lock states
1506** are inserted in between. The locking might fail on one of the later
1507** transitions leaving the lock state different from what it started but
1508** still short of its goal. The following chart shows the allowed
1509** transitions and the inserted intermediate states:
1510**
1511** UNLOCKED -> SHARED
1512** SHARED -> RESERVED
1513** SHARED -> (PENDING) -> EXCLUSIVE
1514** RESERVED -> (PENDING) -> EXCLUSIVE
1515** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001516**
drha6abd042004-06-09 17:37:22 +00001517** This routine will only increase a lock. Use the sqlite3OsUnlock()
1518** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001519*/
drh308c2a52010-05-14 11:30:18 +00001520static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001521 /* The following describes the implementation of the various locks and
1522 ** lock transitions in terms of the POSIX advisory shared and exclusive
1523 ** lock primitives (called read-locks and write-locks below, to avoid
1524 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001525 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001526 ** accessing the same database file, in case that is ever required.
1527 **
1528 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1529 ** byte', each single bytes at well known offsets, and the 'shared byte
1530 ** range', a range of 510 bytes at a well known offset.
1531 **
1532 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001533 ** byte'. If this is successful, 'shared byte range' is read-locked
1534 ** and the lock on the 'pending byte' released. (Legacy note: When
1535 ** SQLite was first developed, Windows95 systems were still very common,
1536 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1537 ** single randomly selected by from the 'shared byte range' is locked.
1538 ** Windows95 is now pretty much extinct, but this work-around for the
1539 ** lack of shared-locks on Windows95 lives on, for backwards
1540 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001541 **
danielk197790ba3bd2004-06-25 08:32:25 +00001542 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1543 ** A RESERVED lock is implemented by grabbing a write-lock on the
1544 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001545 **
1546 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001547 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1548 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1549 ** obtained, but existing SHARED locks are allowed to persist. A process
1550 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1551 ** This property is used by the algorithm for rolling back a journal file
1552 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001553 **
danielk197790ba3bd2004-06-25 08:32:25 +00001554 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1555 ** implemented by obtaining a write-lock on the entire 'shared byte
1556 ** range'. Since all other locks require a read-lock on one of the bytes
1557 ** within this range, this ensures that no other locks are held on the
1558 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001559 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001560 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001561 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001562 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001563 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001564 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001565
drh054889e2005-11-30 03:20:31 +00001566 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001567 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1568 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001569 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001570 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001571
1572 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001573 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001574 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001575 */
drh308c2a52010-05-14 11:30:18 +00001576 if( pFile->eFileLock>=eFileLock ){
1577 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1578 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001579 return SQLITE_OK;
1580 }
1581
drh0c2694b2009-09-03 16:23:44 +00001582 /* Make sure the locking sequence is correct.
1583 ** (1) We never move from unlocked to anything higher than shared lock.
1584 ** (2) SQLite never explicitly requests a pendig lock.
1585 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001586 */
drh308c2a52010-05-14 11:30:18 +00001587 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1588 assert( eFileLock!=PENDING_LOCK );
1589 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001590
drh8af6c222010-05-14 12:43:01 +00001591 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001592 */
drh6c7d5c52008-11-21 20:32:33 +00001593 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001594 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001595
danielk1977ad94b582007-08-20 06:44:22 +00001596 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001597 ** handle that precludes the requested lock, return BUSY.
1598 */
drh8af6c222010-05-14 12:43:01 +00001599 if( (pFile->eFileLock!=pInode->eFileLock &&
1600 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001601 ){
1602 rc = SQLITE_BUSY;
1603 goto end_lock;
1604 }
1605
1606 /* If a SHARED lock is requested, and some thread using this PID already
1607 ** has a SHARED or RESERVED lock, then increment reference counts and
1608 ** return SQLITE_OK.
1609 */
drh308c2a52010-05-14 11:30:18 +00001610 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001611 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001612 assert( eFileLock==SHARED_LOCK );
1613 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001614 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001615 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001616 pInode->nShared++;
1617 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001618 goto end_lock;
1619 }
1620
danielk19779a1d0ab2004-06-01 14:09:28 +00001621
drh3cde3bb2004-06-12 02:17:14 +00001622 /* A PENDING lock is needed before acquiring a SHARED lock and before
1623 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1624 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001625 */
drh0c2694b2009-09-03 16:23:44 +00001626 lock.l_len = 1L;
1627 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001628 if( eFileLock==SHARED_LOCK
1629 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001630 ){
drh308c2a52010-05-14 11:30:18 +00001631 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001632 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001633 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001634 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001635 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001636 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001637 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001638 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001639 goto end_lock;
1640 }
drh3cde3bb2004-06-12 02:17:14 +00001641 }
1642
1643
1644 /* If control gets to this point, then actually go ahead and make
1645 ** operating system calls for the specified lock.
1646 */
drh308c2a52010-05-14 11:30:18 +00001647 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001648 assert( pInode->nShared==0 );
1649 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001650 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001651
drh2ac3ee92004-06-07 16:27:46 +00001652 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001653 lock.l_start = SHARED_FIRST;
1654 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001655 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001656 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001657 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001658 }
dan661d71a2011-03-30 19:08:03 +00001659
drh2ac3ee92004-06-07 16:27:46 +00001660 /* Drop the temporary PENDING lock */
1661 lock.l_start = PENDING_BYTE;
1662 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001663 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001664 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1665 /* This could happen with a network mount */
1666 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001667 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001668 }
dan661d71a2011-03-30 19:08:03 +00001669
1670 if( rc ){
1671 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001672 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001673 }
dan661d71a2011-03-30 19:08:03 +00001674 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001675 }else{
drh308c2a52010-05-14 11:30:18 +00001676 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001677 pInode->nLock++;
1678 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001679 }
drh8af6c222010-05-14 12:43:01 +00001680 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001681 /* We are trying for an exclusive lock but another thread in this
1682 ** same process is still holding a shared lock. */
1683 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001684 }else{
drh3cde3bb2004-06-12 02:17:14 +00001685 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001686 ** assumed that there is a SHARED or greater lock on the file
1687 ** already.
1688 */
drh308c2a52010-05-14 11:30:18 +00001689 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001690 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001691
1692 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1693 if( eFileLock==RESERVED_LOCK ){
1694 lock.l_start = RESERVED_BYTE;
1695 lock.l_len = 1L;
1696 }else{
1697 lock.l_start = SHARED_FIRST;
1698 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001699 }
dan661d71a2011-03-30 19:08:03 +00001700
1701 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001702 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001703 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001704 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001705 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001706 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001707 }
drhbbd42a62004-05-22 17:41:58 +00001708 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001709
drh8f941bc2009-01-14 23:03:40 +00001710
drhd3d8c042012-05-29 17:02:40 +00001711#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001712 /* Set up the transaction-counter change checking flags when
1713 ** transitioning from a SHARED to a RESERVED lock. The change
1714 ** from SHARED to RESERVED marks the beginning of a normal
1715 ** write operation (not a hot journal rollback).
1716 */
1717 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001718 && pFile->eFileLock<=SHARED_LOCK
1719 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001720 ){
1721 pFile->transCntrChng = 0;
1722 pFile->dbUpdate = 0;
1723 pFile->inNormalWrite = 1;
1724 }
1725#endif
1726
1727
danielk1977ecb2a962004-06-02 06:30:16 +00001728 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001729 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001730 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001731 }else if( eFileLock==EXCLUSIVE_LOCK ){
1732 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001733 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001734 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001735
1736end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001737 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001738 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1739 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001740 return rc;
1741}
1742
1743/*
dan08da86a2009-08-21 17:18:03 +00001744** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001745** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001746*/
1747static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001748 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001749 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001750 p->pNext = pInode->pUnused;
1751 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001752 pFile->h = -1;
1753 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001754}
1755
1756/*
drh308c2a52010-05-14 11:30:18 +00001757** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001758** must be either NO_LOCK or SHARED_LOCK.
1759**
1760** If the locking level of the file descriptor is already at or below
1761** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001762**
1763** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1764** the byte range is divided into 2 parts and the first part is unlocked then
1765** set to a read lock, then the other part is simply unlocked. This works
1766** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1767** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001768*/
drha7e61d82011-03-12 17:02:57 +00001769static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001770 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001771 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001772 struct flock lock;
1773 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001774
drh054889e2005-11-30 03:20:31 +00001775 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001776 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001777 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001778 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001779
drh308c2a52010-05-14 11:30:18 +00001780 assert( eFileLock<=SHARED_LOCK );
1781 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001782 return SQLITE_OK;
1783 }
drh6c7d5c52008-11-21 20:32:33 +00001784 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001785 pInode = pFile->pInode;
1786 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001787 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001788 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001789
drhd3d8c042012-05-29 17:02:40 +00001790#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001791 /* When reducing a lock such that other processes can start
1792 ** reading the database file again, make sure that the
1793 ** transaction counter was updated if any part of the database
1794 ** file changed. If the transaction counter is not updated,
1795 ** other connections to the same file might not realize that
1796 ** the file has changed and hence might not know to flush their
1797 ** cache. The use of a stale cache can lead to database corruption.
1798 */
drh8f941bc2009-01-14 23:03:40 +00001799 pFile->inNormalWrite = 0;
1800#endif
1801
drh7ed97b92010-01-20 13:07:21 +00001802 /* downgrading to a shared lock on NFS involves clearing the write lock
1803 ** before establishing the readlock - to avoid a race condition we downgrade
1804 ** the lock in 2 blocks, so that part of the range will be covered by a
1805 ** write lock until the rest is covered by a read lock:
1806 ** 1: [WWWWW]
1807 ** 2: [....W]
1808 ** 3: [RRRRW]
1809 ** 4: [RRRR.]
1810 */
drh308c2a52010-05-14 11:30:18 +00001811 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001812#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001813 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001814 assert( handleNFSUnlock==0 );
1815#endif
1816#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001817 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001818 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001819 off_t divSize = SHARED_SIZE - 1;
1820
1821 lock.l_type = F_UNLCK;
1822 lock.l_whence = SEEK_SET;
1823 lock.l_start = SHARED_FIRST;
1824 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001825 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001826 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001827 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001828 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001829 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001830 }
drh7ed97b92010-01-20 13:07:21 +00001831 lock.l_type = F_RDLCK;
1832 lock.l_whence = SEEK_SET;
1833 lock.l_start = SHARED_FIRST;
1834 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001835 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001836 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001837 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1838 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001839 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001840 }
1841 goto end_unlock;
1842 }
1843 lock.l_type = F_UNLCK;
1844 lock.l_whence = SEEK_SET;
1845 lock.l_start = SHARED_FIRST+divSize;
1846 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001847 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001848 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001849 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001850 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001851 goto end_unlock;
1852 }
drh30f776f2011-02-25 03:25:07 +00001853 }else
1854#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1855 {
drh7ed97b92010-01-20 13:07:21 +00001856 lock.l_type = F_RDLCK;
1857 lock.l_whence = SEEK_SET;
1858 lock.l_start = SHARED_FIRST;
1859 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001860 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001861 /* In theory, the call to unixFileLock() cannot fail because another
1862 ** process is holding an incompatible lock. If it does, this
1863 ** indicates that the other process is not following the locking
1864 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1865 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1866 ** an assert to fail). */
1867 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001868 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001869 goto end_unlock;
1870 }
drh9c105bb2004-10-02 20:38:28 +00001871 }
1872 }
drhbbd42a62004-05-22 17:41:58 +00001873 lock.l_type = F_UNLCK;
1874 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001875 lock.l_start = PENDING_BYTE;
1876 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001877 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001878 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001879 }else{
danea83bc62011-04-01 11:56:32 +00001880 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001881 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001882 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001883 }
drhbbd42a62004-05-22 17:41:58 +00001884 }
drh308c2a52010-05-14 11:30:18 +00001885 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001886 /* Decrement the shared lock counter. Release the lock using an
1887 ** OS call only when all threads in this same process have released
1888 ** the lock.
1889 */
drh8af6c222010-05-14 12:43:01 +00001890 pInode->nShared--;
1891 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001892 lock.l_type = F_UNLCK;
1893 lock.l_whence = SEEK_SET;
1894 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001895 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001896 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001897 }else{
danea83bc62011-04-01 11:56:32 +00001898 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001899 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001900 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001901 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001902 }
drha6abd042004-06-09 17:37:22 +00001903 }
1904
drhbbd42a62004-05-22 17:41:58 +00001905 /* Decrement the count of locks against this same file. When the
1906 ** count reaches zero, close any other file descriptors whose close
1907 ** was deferred because of outstanding locks.
1908 */
drh8af6c222010-05-14 12:43:01 +00001909 pInode->nLock--;
1910 assert( pInode->nLock>=0 );
1911 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001912 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001913 }
1914 }
drhf2f105d2012-08-20 15:53:54 +00001915
aswift5b1a2562008-08-22 00:22:35 +00001916end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001917 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001918 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001919 return rc;
drhbbd42a62004-05-22 17:41:58 +00001920}
1921
1922/*
drh308c2a52010-05-14 11:30:18 +00001923** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001924** must be either NO_LOCK or SHARED_LOCK.
1925**
1926** If the locking level of the file descriptor is already at or below
1927** the requested locking level, this routine is a no-op.
1928*/
drh308c2a52010-05-14 11:30:18 +00001929static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001930#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001931 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001932#endif
drha7e61d82011-03-12 17:02:57 +00001933 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001934}
1935
mistachkine98844f2013-08-24 00:59:24 +00001936#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001937static int unixMapfile(unixFile *pFd, i64 nByte);
1938static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001939#endif
danf23da962013-03-23 21:00:41 +00001940
drh7ed97b92010-01-20 13:07:21 +00001941/*
danielk1977e339d652008-06-28 11:23:00 +00001942** This function performs the parts of the "close file" operation
1943** common to all locking schemes. It closes the directory and file
1944** handles, if they are valid, and sets all fields of the unixFile
1945** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001946**
1947** It is *not* necessary to hold the mutex when this routine is called,
1948** even on VxWorks. A mutex will be acquired on VxWorks by the
1949** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001950*/
1951static int closeUnixFile(sqlite3_file *id){
1952 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001953#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001954 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001955#endif
dan661d71a2011-03-30 19:08:03 +00001956 if( pFile->h>=0 ){
1957 robust_close(pFile, pFile->h, __LINE__);
1958 pFile->h = -1;
1959 }
1960#if OS_VXWORKS
1961 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001962 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001963 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001964 }
1965 vxworksReleaseFileId(pFile->pId);
1966 pFile->pId = 0;
1967 }
1968#endif
drh0bdbc902014-06-16 18:35:06 +00001969#ifdef SQLITE_UNLINK_AFTER_CLOSE
1970 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1971 osUnlink(pFile->zPath);
1972 sqlite3_free(*(char**)&pFile->zPath);
1973 pFile->zPath = 0;
1974 }
1975#endif
dan661d71a2011-03-30 19:08:03 +00001976 OSTRACE(("CLOSE %-3d\n", pFile->h));
1977 OpenCounter(-1);
1978 sqlite3_free(pFile->pUnused);
1979 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001980 return SQLITE_OK;
1981}
1982
1983/*
danielk1977e3026632004-06-22 11:29:02 +00001984** Close a file.
1985*/
danielk197762079062007-08-15 17:08:46 +00001986static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001987 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001988 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001989 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001990 unixUnlock(id, NO_LOCK);
1991 unixEnterMutex();
1992
1993 /* unixFile.pInode is always valid here. Otherwise, a different close
1994 ** routine (e.g. nolockClose()) would be called instead.
1995 */
1996 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1997 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1998 /* If there are outstanding locks, do not actually close the file just
1999 ** yet because that would clear those locks. Instead, add the file
2000 ** descriptor to pInode->pUnused list. It will be automatically closed
2001 ** when the last lock is cleared.
2002 */
2003 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002004 }
dan661d71a2011-03-30 19:08:03 +00002005 releaseInodeInfo(pFile);
2006 rc = closeUnixFile(id);
2007 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002008 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002009}
2010
drh734c9862008-11-28 15:37:20 +00002011/************** End of the posix advisory lock implementation *****************
2012******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002013
drh734c9862008-11-28 15:37:20 +00002014/******************************************************************************
2015****************************** No-op Locking **********************************
2016**
2017** Of the various locking implementations available, this is by far the
2018** simplest: locking is ignored. No attempt is made to lock the database
2019** file for reading or writing.
2020**
2021** This locking mode is appropriate for use on read-only databases
2022** (ex: databases that are burned into CD-ROM, for example.) It can
2023** also be used if the application employs some external mechanism to
2024** prevent simultaneous access of the same database by two or more
2025** database connections. But there is a serious risk of database
2026** corruption if this locking mode is used in situations where multiple
2027** database connections are accessing the same database file at the same
2028** time and one or more of those connections are writing.
2029*/
drhbfe66312006-10-03 17:40:40 +00002030
drh734c9862008-11-28 15:37:20 +00002031static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2032 UNUSED_PARAMETER(NotUsed);
2033 *pResOut = 0;
2034 return SQLITE_OK;
2035}
drh734c9862008-11-28 15:37:20 +00002036static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2037 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2038 return SQLITE_OK;
2039}
drh734c9862008-11-28 15:37:20 +00002040static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2041 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2042 return SQLITE_OK;
2043}
2044
2045/*
drh9b35ea62008-11-29 02:20:26 +00002046** Close the file.
drh734c9862008-11-28 15:37:20 +00002047*/
2048static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002049 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002050}
2051
2052/******************* End of the no-op lock implementation *********************
2053******************************************************************************/
2054
2055/******************************************************************************
2056************************* Begin dot-file Locking ******************************
2057**
mistachkin48864df2013-03-21 21:20:32 +00002058** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002059** files (really a directory) to control access to the database. This works
2060** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002061**
2062** (1) There is zero concurrency. A single reader blocks all other
2063** connections from reading or writing the database.
2064**
2065** (2) An application crash or power loss can leave stale lock files
2066** sitting around that need to be cleared manually.
2067**
2068** Nevertheless, a dotlock is an appropriate locking mode for use if no
2069** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002070**
drh9ef6bc42011-11-04 02:24:02 +00002071** Dotfile locking works by creating a subdirectory in the same directory as
2072** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002073** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002074** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002075*/
2076
2077/*
2078** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002079** lock directory.
drh734c9862008-11-28 15:37:20 +00002080*/
2081#define DOTLOCK_SUFFIX ".lock"
2082
drh7708e972008-11-29 00:56:52 +00002083/*
2084** This routine checks if there is a RESERVED lock held on the specified
2085** file by this or any other process. If such a lock is held, set *pResOut
2086** to a non-zero value otherwise *pResOut is set to zero. The return value
2087** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2088**
2089** In dotfile locking, either a lock exists or it does not. So in this
2090** variation of CheckReservedLock(), *pResOut is set to true if any lock
2091** is held on the file and false if the file is unlocked.
2092*/
drh734c9862008-11-28 15:37:20 +00002093static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2094 int rc = SQLITE_OK;
2095 int reserved = 0;
2096 unixFile *pFile = (unixFile*)id;
2097
2098 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2099
2100 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002101 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002102 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002103 *pResOut = reserved;
2104 return rc;
2105}
2106
drh7708e972008-11-29 00:56:52 +00002107/*
drh308c2a52010-05-14 11:30:18 +00002108** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002109** of the following:
2110**
2111** (1) SHARED_LOCK
2112** (2) RESERVED_LOCK
2113** (3) PENDING_LOCK
2114** (4) EXCLUSIVE_LOCK
2115**
2116** Sometimes when requesting one lock state, additional lock states
2117** are inserted in between. The locking might fail on one of the later
2118** transitions leaving the lock state different from what it started but
2119** still short of its goal. The following chart shows the allowed
2120** transitions and the inserted intermediate states:
2121**
2122** UNLOCKED -> SHARED
2123** SHARED -> RESERVED
2124** SHARED -> (PENDING) -> EXCLUSIVE
2125** RESERVED -> (PENDING) -> EXCLUSIVE
2126** PENDING -> EXCLUSIVE
2127**
2128** This routine will only increase a lock. Use the sqlite3OsUnlock()
2129** routine to lower a locking level.
2130**
2131** With dotfile locking, we really only support state (4): EXCLUSIVE.
2132** But we track the other locking levels internally.
2133*/
drh308c2a52010-05-14 11:30:18 +00002134static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002135 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002136 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002137 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002138
drh7708e972008-11-29 00:56:52 +00002139
2140 /* If we have any lock, then the lock file already exists. All we have
2141 ** to do is adjust our internal record of the lock level.
2142 */
drh308c2a52010-05-14 11:30:18 +00002143 if( pFile->eFileLock > NO_LOCK ){
2144 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002145 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002146#ifdef HAVE_UTIME
2147 utime(zLockFile, NULL);
2148#else
drh734c9862008-11-28 15:37:20 +00002149 utimes(zLockFile, NULL);
2150#endif
drh7708e972008-11-29 00:56:52 +00002151 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002152 }
2153
2154 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002155 rc = osMkdir(zLockFile, 0777);
2156 if( rc<0 ){
2157 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002158 int tErrno = errno;
2159 if( EEXIST == tErrno ){
2160 rc = SQLITE_BUSY;
2161 } else {
2162 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002163 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002164 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002165 }
2166 }
drh7708e972008-11-29 00:56:52 +00002167 return rc;
drh734c9862008-11-28 15:37:20 +00002168 }
drh734c9862008-11-28 15:37:20 +00002169
2170 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002171 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002172 return rc;
2173}
2174
drh7708e972008-11-29 00:56:52 +00002175/*
drh308c2a52010-05-14 11:30:18 +00002176** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002177** must be either NO_LOCK or SHARED_LOCK.
2178**
2179** If the locking level of the file descriptor is already at or below
2180** the requested locking level, this routine is a no-op.
2181**
2182** When the locking level reaches NO_LOCK, delete the lock file.
2183*/
drh308c2a52010-05-14 11:30:18 +00002184static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002185 unixFile *pFile = (unixFile*)id;
2186 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002187 int rc;
drh734c9862008-11-28 15:37:20 +00002188
2189 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002190 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002191 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002192 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002193
2194 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002195 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002196 return SQLITE_OK;
2197 }
drh7708e972008-11-29 00:56:52 +00002198
2199 /* To downgrade to shared, simply update our internal notion of the
2200 ** lock state. No need to mess with the file on disk.
2201 */
drh308c2a52010-05-14 11:30:18 +00002202 if( eFileLock==SHARED_LOCK ){
2203 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002204 return SQLITE_OK;
2205 }
2206
drh7708e972008-11-29 00:56:52 +00002207 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002208 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002209 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002210 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002211 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002212 if( tErrno==ENOENT ){
2213 rc = SQLITE_OK;
2214 }else{
danea83bc62011-04-01 11:56:32 +00002215 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002216 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002217 }
2218 return rc;
2219 }
drh308c2a52010-05-14 11:30:18 +00002220 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002221 return SQLITE_OK;
2222}
2223
2224/*
drh9b35ea62008-11-29 02:20:26 +00002225** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002226*/
2227static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002228 unixFile *pFile = (unixFile*)id;
2229 assert( id!=0 );
2230 dotlockUnlock(id, NO_LOCK);
2231 sqlite3_free(pFile->lockingContext);
2232 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002233}
2234/****************** End of the dot-file lock implementation *******************
2235******************************************************************************/
2236
2237/******************************************************************************
2238************************** Begin flock Locking ********************************
2239**
2240** Use the flock() system call to do file locking.
2241**
drh6b9d6dd2008-12-03 19:34:47 +00002242** flock() locking is like dot-file locking in that the various
2243** fine-grain locking levels supported by SQLite are collapsed into
2244** a single exclusive lock. In other words, SHARED, RESERVED, and
2245** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2246** still works when you do this, but concurrency is reduced since
2247** only a single process can be reading the database at a time.
2248**
drhe89b2912015-03-03 20:42:01 +00002249** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002250*/
drhe89b2912015-03-03 20:42:01 +00002251#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002252
drh6b9d6dd2008-12-03 19:34:47 +00002253/*
drhff812312011-02-23 13:33:46 +00002254** Retry flock() calls that fail with EINTR
2255*/
2256#ifdef EINTR
2257static int robust_flock(int fd, int op){
2258 int rc;
2259 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2260 return rc;
2261}
2262#else
drh5c819272011-02-23 14:00:12 +00002263# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002264#endif
2265
2266
2267/*
drh6b9d6dd2008-12-03 19:34:47 +00002268** This routine checks if there is a RESERVED lock held on the specified
2269** file by this or any other process. If such a lock is held, set *pResOut
2270** to a non-zero value otherwise *pResOut is set to zero. The return value
2271** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2272*/
drh734c9862008-11-28 15:37:20 +00002273static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2274 int rc = SQLITE_OK;
2275 int reserved = 0;
2276 unixFile *pFile = (unixFile*)id;
2277
2278 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2279
2280 assert( pFile );
2281
2282 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002283 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002284 reserved = 1;
2285 }
2286
2287 /* Otherwise see if some other process holds it. */
2288 if( !reserved ){
2289 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002290 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002291 if( !lrc ){
2292 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002293 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002294 if ( lrc ) {
2295 int tErrno = errno;
2296 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002297 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002298 storeLastErrno(pFile, tErrno);
2299 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002300 }
2301 } else {
2302 int tErrno = errno;
2303 reserved = 1;
2304 /* someone else might have it reserved */
2305 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2306 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002307 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002308 rc = lrc;
2309 }
2310 }
2311 }
drh308c2a52010-05-14 11:30:18 +00002312 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002313
2314#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2315 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2316 rc = SQLITE_OK;
2317 reserved=1;
2318 }
2319#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2320 *pResOut = reserved;
2321 return rc;
2322}
2323
drh6b9d6dd2008-12-03 19:34:47 +00002324/*
drh308c2a52010-05-14 11:30:18 +00002325** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002326** of the following:
2327**
2328** (1) SHARED_LOCK
2329** (2) RESERVED_LOCK
2330** (3) PENDING_LOCK
2331** (4) EXCLUSIVE_LOCK
2332**
2333** Sometimes when requesting one lock state, additional lock states
2334** are inserted in between. The locking might fail on one of the later
2335** transitions leaving the lock state different from what it started but
2336** still short of its goal. The following chart shows the allowed
2337** transitions and the inserted intermediate states:
2338**
2339** UNLOCKED -> SHARED
2340** SHARED -> RESERVED
2341** SHARED -> (PENDING) -> EXCLUSIVE
2342** RESERVED -> (PENDING) -> EXCLUSIVE
2343** PENDING -> EXCLUSIVE
2344**
2345** flock() only really support EXCLUSIVE locks. We track intermediate
2346** lock states in the sqlite3_file structure, but all locks SHARED or
2347** above are really EXCLUSIVE locks and exclude all other processes from
2348** access the file.
2349**
2350** This routine will only increase a lock. Use the sqlite3OsUnlock()
2351** routine to lower a locking level.
2352*/
drh308c2a52010-05-14 11:30:18 +00002353static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002354 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002355 unixFile *pFile = (unixFile*)id;
2356
2357 assert( pFile );
2358
2359 /* if we already have a lock, it is exclusive.
2360 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002361 if (pFile->eFileLock > NO_LOCK) {
2362 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002363 return SQLITE_OK;
2364 }
2365
2366 /* grab an exclusive lock */
2367
drhff812312011-02-23 13:33:46 +00002368 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002369 int tErrno = errno;
2370 /* didn't get, must be busy */
2371 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2372 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002373 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002374 }
2375 } else {
2376 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002377 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002378 }
drh308c2a52010-05-14 11:30:18 +00002379 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2380 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002381#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2382 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2383 rc = SQLITE_BUSY;
2384 }
2385#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2386 return rc;
2387}
2388
drh6b9d6dd2008-12-03 19:34:47 +00002389
2390/*
drh308c2a52010-05-14 11:30:18 +00002391** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002392** must be either NO_LOCK or SHARED_LOCK.
2393**
2394** If the locking level of the file descriptor is already at or below
2395** the requested locking level, this routine is a no-op.
2396*/
drh308c2a52010-05-14 11:30:18 +00002397static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002398 unixFile *pFile = (unixFile*)id;
2399
2400 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002401 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002402 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002403 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002404
2405 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002406 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002407 return SQLITE_OK;
2408 }
2409
2410 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002411 if (eFileLock==SHARED_LOCK) {
2412 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002413 return SQLITE_OK;
2414 }
2415
2416 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002417 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002418#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002419 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002420#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002421 return SQLITE_IOERR_UNLOCK;
2422 }else{
drh308c2a52010-05-14 11:30:18 +00002423 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002424 return SQLITE_OK;
2425 }
2426}
2427
2428/*
2429** Close a file.
2430*/
2431static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002432 assert( id!=0 );
2433 flockUnlock(id, NO_LOCK);
2434 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002435}
2436
2437#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2438
2439/******************* End of the flock lock implementation *********************
2440******************************************************************************/
2441
2442/******************************************************************************
2443************************ Begin Named Semaphore Locking ************************
2444**
2445** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002446**
2447** Semaphore locking is like dot-lock and flock in that it really only
2448** supports EXCLUSIVE locking. Only a single process can read or write
2449** the database file at a time. This reduces potential concurrency, but
2450** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002451*/
2452#if OS_VXWORKS
2453
drh6b9d6dd2008-12-03 19:34:47 +00002454/*
2455** This routine checks if there is a RESERVED lock held on the specified
2456** file by this or any other process. If such a lock is held, set *pResOut
2457** to a non-zero value otherwise *pResOut is set to zero. The return value
2458** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2459*/
drh8cd5b252015-03-02 22:06:43 +00002460static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002461 int rc = SQLITE_OK;
2462 int reserved = 0;
2463 unixFile *pFile = (unixFile*)id;
2464
2465 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2466
2467 assert( pFile );
2468
2469 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002470 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002471 reserved = 1;
2472 }
2473
2474 /* Otherwise see if some other process holds it. */
2475 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002476 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002477
2478 if( sem_trywait(pSem)==-1 ){
2479 int tErrno = errno;
2480 if( EAGAIN != tErrno ){
2481 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002482 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002483 } else {
2484 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002485 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002486 }
2487 }else{
2488 /* we could have it if we want it */
2489 sem_post(pSem);
2490 }
2491 }
drh308c2a52010-05-14 11:30:18 +00002492 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002493
2494 *pResOut = reserved;
2495 return rc;
2496}
2497
drh6b9d6dd2008-12-03 19:34:47 +00002498/*
drh308c2a52010-05-14 11:30:18 +00002499** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002500** of the following:
2501**
2502** (1) SHARED_LOCK
2503** (2) RESERVED_LOCK
2504** (3) PENDING_LOCK
2505** (4) EXCLUSIVE_LOCK
2506**
2507** Sometimes when requesting one lock state, additional lock states
2508** are inserted in between. The locking might fail on one of the later
2509** transitions leaving the lock state different from what it started but
2510** still short of its goal. The following chart shows the allowed
2511** transitions and the inserted intermediate states:
2512**
2513** UNLOCKED -> SHARED
2514** SHARED -> RESERVED
2515** SHARED -> (PENDING) -> EXCLUSIVE
2516** RESERVED -> (PENDING) -> EXCLUSIVE
2517** PENDING -> EXCLUSIVE
2518**
2519** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2520** lock states in the sqlite3_file structure, but all locks SHARED or
2521** above are really EXCLUSIVE locks and exclude all other processes from
2522** access the file.
2523**
2524** This routine will only increase a lock. Use the sqlite3OsUnlock()
2525** routine to lower a locking level.
2526*/
drh8cd5b252015-03-02 22:06:43 +00002527static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002528 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002529 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002530 int rc = SQLITE_OK;
2531
2532 /* if we already have a lock, it is exclusive.
2533 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002534 if (pFile->eFileLock > NO_LOCK) {
2535 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002536 rc = SQLITE_OK;
2537 goto sem_end_lock;
2538 }
2539
2540 /* lock semaphore now but bail out when already locked. */
2541 if( sem_trywait(pSem)==-1 ){
2542 rc = SQLITE_BUSY;
2543 goto sem_end_lock;
2544 }
2545
2546 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002547 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002548
2549 sem_end_lock:
2550 return rc;
2551}
2552
drh6b9d6dd2008-12-03 19:34:47 +00002553/*
drh308c2a52010-05-14 11:30:18 +00002554** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002555** must be either NO_LOCK or SHARED_LOCK.
2556**
2557** If the locking level of the file descriptor is already at or below
2558** the requested locking level, this routine is a no-op.
2559*/
drh8cd5b252015-03-02 22:06:43 +00002560static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002561 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002562 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002563
2564 assert( pFile );
2565 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002566 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002567 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002568 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002569
2570 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002571 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002572 return SQLITE_OK;
2573 }
2574
2575 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002576 if (eFileLock==SHARED_LOCK) {
2577 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002578 return SQLITE_OK;
2579 }
2580
2581 /* no, really unlock. */
2582 if ( sem_post(pSem)==-1 ) {
2583 int rc, tErrno = errno;
2584 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2585 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002586 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002587 }
2588 return rc;
2589 }
drh308c2a52010-05-14 11:30:18 +00002590 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002591 return SQLITE_OK;
2592}
2593
2594/*
2595 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002596 */
drh8cd5b252015-03-02 22:06:43 +00002597static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002598 if( id ){
2599 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002600 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002601 assert( pFile );
2602 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002603 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002604 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002605 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002606 }
2607 return SQLITE_OK;
2608}
2609
2610#endif /* OS_VXWORKS */
2611/*
2612** Named semaphore locking is only available on VxWorks.
2613**
2614*************** End of the named semaphore lock implementation ****************
2615******************************************************************************/
2616
2617
2618/******************************************************************************
2619*************************** Begin AFP Locking *********************************
2620**
2621** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2622** on Apple Macintosh computers - both OS9 and OSX.
2623**
2624** Third-party implementations of AFP are available. But this code here
2625** only works on OSX.
2626*/
2627
drhd2cb50b2009-01-09 21:41:17 +00002628#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002629/*
2630** The afpLockingContext structure contains all afp lock specific state
2631*/
drhbfe66312006-10-03 17:40:40 +00002632typedef struct afpLockingContext afpLockingContext;
2633struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002634 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002635 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002636};
2637
2638struct ByteRangeLockPB2
2639{
2640 unsigned long long offset; /* offset to first byte to lock */
2641 unsigned long long length; /* nbr of bytes to lock */
2642 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2643 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2644 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2645 int fd; /* file desc to assoc this lock with */
2646};
2647
drhfd131da2007-08-07 17:13:03 +00002648#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002649
drh6b9d6dd2008-12-03 19:34:47 +00002650/*
2651** This is a utility for setting or clearing a bit-range lock on an
2652** AFP filesystem.
2653**
2654** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2655*/
2656static int afpSetLock(
2657 const char *path, /* Name of the file to be locked or unlocked */
2658 unixFile *pFile, /* Open file descriptor on path */
2659 unsigned long long offset, /* First byte to be locked */
2660 unsigned long long length, /* Number of bytes to lock */
2661 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002662){
drh6b9d6dd2008-12-03 19:34:47 +00002663 struct ByteRangeLockPB2 pb;
2664 int err;
drhbfe66312006-10-03 17:40:40 +00002665
2666 pb.unLockFlag = setLockFlag ? 0 : 1;
2667 pb.startEndFlag = 0;
2668 pb.offset = offset;
2669 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002670 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002671
drh308c2a52010-05-14 11:30:18 +00002672 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002673 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002674 offset, length));
drhbfe66312006-10-03 17:40:40 +00002675 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2676 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002677 int rc;
2678 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002679 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2680 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002681#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2682 rc = SQLITE_BUSY;
2683#else
drh734c9862008-11-28 15:37:20 +00002684 rc = sqliteErrorFromPosixError(tErrno,
2685 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002686#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002687 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002688 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002689 }
2690 return rc;
drhbfe66312006-10-03 17:40:40 +00002691 } else {
aswift5b1a2562008-08-22 00:22:35 +00002692 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002693 }
2694}
2695
drh6b9d6dd2008-12-03 19:34:47 +00002696/*
2697** This routine checks if there is a RESERVED lock held on the specified
2698** file by this or any other process. If such a lock is held, set *pResOut
2699** to a non-zero value otherwise *pResOut is set to zero. The return value
2700** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2701*/
danielk1977e339d652008-06-28 11:23:00 +00002702static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002703 int rc = SQLITE_OK;
2704 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002705 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002706 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002707
aswift5b1a2562008-08-22 00:22:35 +00002708 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2709
2710 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002711 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002712 if( context->reserved ){
2713 *pResOut = 1;
2714 return SQLITE_OK;
2715 }
drh8af6c222010-05-14 12:43:01 +00002716 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002717
2718 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002719 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002720 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002721 }
2722
2723 /* Otherwise see if some other process holds it.
2724 */
aswift5b1a2562008-08-22 00:22:35 +00002725 if( !reserved ){
2726 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002727 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002728 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002729 /* if we succeeded in taking the reserved lock, unlock it to restore
2730 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002731 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002732 } else {
2733 /* if we failed to get the lock then someone else must have it */
2734 reserved = 1;
2735 }
2736 if( IS_LOCK_ERROR(lrc) ){
2737 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002738 }
2739 }
drhbfe66312006-10-03 17:40:40 +00002740
drh7ed97b92010-01-20 13:07:21 +00002741 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002742 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002743
2744 *pResOut = reserved;
2745 return rc;
drhbfe66312006-10-03 17:40:40 +00002746}
2747
drh6b9d6dd2008-12-03 19:34:47 +00002748/*
drh308c2a52010-05-14 11:30:18 +00002749** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002750** of the following:
2751**
2752** (1) SHARED_LOCK
2753** (2) RESERVED_LOCK
2754** (3) PENDING_LOCK
2755** (4) EXCLUSIVE_LOCK
2756**
2757** Sometimes when requesting one lock state, additional lock states
2758** are inserted in between. The locking might fail on one of the later
2759** transitions leaving the lock state different from what it started but
2760** still short of its goal. The following chart shows the allowed
2761** transitions and the inserted intermediate states:
2762**
2763** UNLOCKED -> SHARED
2764** SHARED -> RESERVED
2765** SHARED -> (PENDING) -> EXCLUSIVE
2766** RESERVED -> (PENDING) -> EXCLUSIVE
2767** PENDING -> EXCLUSIVE
2768**
2769** This routine will only increase a lock. Use the sqlite3OsUnlock()
2770** routine to lower a locking level.
2771*/
drh308c2a52010-05-14 11:30:18 +00002772static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002773 int rc = SQLITE_OK;
2774 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002775 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002776 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002777
2778 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002779 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2780 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002781 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002782
drhbfe66312006-10-03 17:40:40 +00002783 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002784 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002785 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002786 */
drh308c2a52010-05-14 11:30:18 +00002787 if( pFile->eFileLock>=eFileLock ){
2788 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2789 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002790 return SQLITE_OK;
2791 }
2792
2793 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002794 ** (1) We never move from unlocked to anything higher than shared lock.
2795 ** (2) SQLite never explicitly requests a pendig lock.
2796 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002797 */
drh308c2a52010-05-14 11:30:18 +00002798 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2799 assert( eFileLock!=PENDING_LOCK );
2800 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002801
drh8af6c222010-05-14 12:43:01 +00002802 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002803 */
drh6c7d5c52008-11-21 20:32:33 +00002804 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002805 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002806
2807 /* If some thread using this PID has a lock via a different unixFile*
2808 ** handle that precludes the requested lock, return BUSY.
2809 */
drh8af6c222010-05-14 12:43:01 +00002810 if( (pFile->eFileLock!=pInode->eFileLock &&
2811 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002812 ){
2813 rc = SQLITE_BUSY;
2814 goto afp_end_lock;
2815 }
2816
2817 /* If a SHARED lock is requested, and some thread using this PID already
2818 ** has a SHARED or RESERVED lock, then increment reference counts and
2819 ** return SQLITE_OK.
2820 */
drh308c2a52010-05-14 11:30:18 +00002821 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002822 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002823 assert( eFileLock==SHARED_LOCK );
2824 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002825 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002826 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002827 pInode->nShared++;
2828 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002829 goto afp_end_lock;
2830 }
drhbfe66312006-10-03 17:40:40 +00002831
2832 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002833 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2834 ** be released.
2835 */
drh308c2a52010-05-14 11:30:18 +00002836 if( eFileLock==SHARED_LOCK
2837 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002838 ){
2839 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002840 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002841 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002842 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002843 goto afp_end_lock;
2844 }
2845 }
2846
2847 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002848 ** operating system calls for the specified lock.
2849 */
drh308c2a52010-05-14 11:30:18 +00002850 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002851 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002852 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002853
drh8af6c222010-05-14 12:43:01 +00002854 assert( pInode->nShared==0 );
2855 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002856
2857 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002858 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002859 /* note that the quality of the randomness doesn't matter that much */
2860 lk = random();
drh8af6c222010-05-14 12:43:01 +00002861 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002862 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002863 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002864 if( IS_LOCK_ERROR(lrc1) ){
2865 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002866 }
aswift5b1a2562008-08-22 00:22:35 +00002867 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002868 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002869
aswift5b1a2562008-08-22 00:22:35 +00002870 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002871 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002872 rc = lrc1;
2873 goto afp_end_lock;
2874 } else if( IS_LOCK_ERROR(lrc2) ){
2875 rc = lrc2;
2876 goto afp_end_lock;
2877 } else if( lrc1 != SQLITE_OK ) {
2878 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002879 } else {
drh308c2a52010-05-14 11:30:18 +00002880 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002881 pInode->nLock++;
2882 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002883 }
drh8af6c222010-05-14 12:43:01 +00002884 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002885 /* We are trying for an exclusive lock but another thread in this
2886 ** same process is still holding a shared lock. */
2887 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002888 }else{
2889 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2890 ** assumed that there is a SHARED or greater lock on the file
2891 ** already.
2892 */
2893 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002894 assert( 0!=pFile->eFileLock );
2895 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002896 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002897 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002898 if( !failed ){
2899 context->reserved = 1;
2900 }
drhbfe66312006-10-03 17:40:40 +00002901 }
drh308c2a52010-05-14 11:30:18 +00002902 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002903 /* Acquire an EXCLUSIVE lock */
2904
2905 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002906 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002907 */
drh6b9d6dd2008-12-03 19:34:47 +00002908 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002909 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002910 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002911 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002912 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002913 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002914 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002915 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002916 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2917 ** a critical I/O error
2918 */
2919 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2920 SQLITE_IOERR_LOCK;
2921 goto afp_end_lock;
2922 }
2923 }else{
aswift5b1a2562008-08-22 00:22:35 +00002924 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002925 }
2926 }
aswift5b1a2562008-08-22 00:22:35 +00002927 if( failed ){
2928 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002929 }
2930 }
2931
2932 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002933 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002934 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002935 }else if( eFileLock==EXCLUSIVE_LOCK ){
2936 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002937 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002938 }
2939
2940afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002941 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002942 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2943 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002944 return rc;
2945}
2946
2947/*
drh308c2a52010-05-14 11:30:18 +00002948** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002949** must be either NO_LOCK or SHARED_LOCK.
2950**
2951** If the locking level of the file descriptor is already at or below
2952** the requested locking level, this routine is a no-op.
2953*/
drh308c2a52010-05-14 11:30:18 +00002954static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002955 int rc = SQLITE_OK;
2956 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002957 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002958 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2959 int skipShared = 0;
2960#ifdef SQLITE_TEST
2961 int h = pFile->h;
2962#endif
drhbfe66312006-10-03 17:40:40 +00002963
2964 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002965 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002966 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002967 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002968
drh308c2a52010-05-14 11:30:18 +00002969 assert( eFileLock<=SHARED_LOCK );
2970 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002971 return SQLITE_OK;
2972 }
drh6c7d5c52008-11-21 20:32:33 +00002973 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002974 pInode = pFile->pInode;
2975 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002976 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002977 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002978 SimulateIOErrorBenign(1);
2979 SimulateIOError( h=(-1) )
2980 SimulateIOErrorBenign(0);
2981
drhd3d8c042012-05-29 17:02:40 +00002982#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002983 /* When reducing a lock such that other processes can start
2984 ** reading the database file again, make sure that the
2985 ** transaction counter was updated if any part of the database
2986 ** file changed. If the transaction counter is not updated,
2987 ** other connections to the same file might not realize that
2988 ** the file has changed and hence might not know to flush their
2989 ** cache. The use of a stale cache can lead to database corruption.
2990 */
2991 assert( pFile->inNormalWrite==0
2992 || pFile->dbUpdate==0
2993 || pFile->transCntrChng==1 );
2994 pFile->inNormalWrite = 0;
2995#endif
aswiftaebf4132008-11-21 00:10:35 +00002996
drh308c2a52010-05-14 11:30:18 +00002997 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002998 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002999 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003000 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003001 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003002 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3003 } else {
3004 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003005 }
3006 }
drh308c2a52010-05-14 11:30:18 +00003007 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003008 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003009 }
drh308c2a52010-05-14 11:30:18 +00003010 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003011 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3012 if( !rc ){
3013 context->reserved = 0;
3014 }
aswiftaebf4132008-11-21 00:10:35 +00003015 }
drh8af6c222010-05-14 12:43:01 +00003016 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3017 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003018 }
aswiftaebf4132008-11-21 00:10:35 +00003019 }
drh308c2a52010-05-14 11:30:18 +00003020 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003021
drh7ed97b92010-01-20 13:07:21 +00003022 /* Decrement the shared lock counter. Release the lock using an
3023 ** OS call only when all threads in this same process have released
3024 ** the lock.
3025 */
drh8af6c222010-05-14 12:43:01 +00003026 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3027 pInode->nShared--;
3028 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003029 SimulateIOErrorBenign(1);
3030 SimulateIOError( h=(-1) )
3031 SimulateIOErrorBenign(0);
3032 if( !skipShared ){
3033 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3034 }
3035 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003036 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003037 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003038 }
3039 }
3040 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003041 pInode->nLock--;
3042 assert( pInode->nLock>=0 );
3043 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003044 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003045 }
3046 }
drhbfe66312006-10-03 17:40:40 +00003047 }
drh7ed97b92010-01-20 13:07:21 +00003048
drh6c7d5c52008-11-21 20:32:33 +00003049 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003050 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003051 return rc;
3052}
3053
3054/*
drh339eb0b2008-03-07 15:34:11 +00003055** Close a file & cleanup AFP specific locking context
3056*/
danielk1977e339d652008-06-28 11:23:00 +00003057static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003058 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003059 unixFile *pFile = (unixFile*)id;
3060 assert( id!=0 );
3061 afpUnlock(id, NO_LOCK);
3062 unixEnterMutex();
3063 if( pFile->pInode && pFile->pInode->nLock ){
3064 /* If there are outstanding locks, do not actually close the file just
3065 ** yet because that would clear those locks. Instead, add the file
3066 ** descriptor to pInode->aPending. It will be automatically closed when
3067 ** the last lock is cleared.
3068 */
3069 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003070 }
drha8de1e12015-11-30 00:05:39 +00003071 releaseInodeInfo(pFile);
3072 sqlite3_free(pFile->lockingContext);
3073 rc = closeUnixFile(id);
3074 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003075 return rc;
drhbfe66312006-10-03 17:40:40 +00003076}
3077
drhd2cb50b2009-01-09 21:41:17 +00003078#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003079/*
3080** The code above is the AFP lock implementation. The code is specific
3081** to MacOSX and does not work on other unix platforms. No alternative
3082** is available. If you don't compile for a mac, then the "unix-afp"
3083** VFS is not available.
3084**
3085********************* End of the AFP lock implementation **********************
3086******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003087
drh7ed97b92010-01-20 13:07:21 +00003088/******************************************************************************
3089*************************** Begin NFS Locking ********************************/
3090
3091#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3092/*
drh308c2a52010-05-14 11:30:18 +00003093 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003094 ** must be either NO_LOCK or SHARED_LOCK.
3095 **
3096 ** If the locking level of the file descriptor is already at or below
3097 ** the requested locking level, this routine is a no-op.
3098 */
drh308c2a52010-05-14 11:30:18 +00003099static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003100 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003101}
3102
3103#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3104/*
3105** The code above is the NFS lock implementation. The code is specific
3106** to MacOSX and does not work on other unix platforms. No alternative
3107** is available.
3108**
3109********************* End of the NFS lock implementation **********************
3110******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003111
3112/******************************************************************************
3113**************** Non-locking sqlite3_file methods *****************************
3114**
3115** The next division contains implementations for all methods of the
3116** sqlite3_file object other than the locking methods. The locking
3117** methods were defined in divisions above (one locking method per
3118** division). Those methods that are common to all locking modes
3119** are gather together into this division.
3120*/
drhbfe66312006-10-03 17:40:40 +00003121
3122/*
drh734c9862008-11-28 15:37:20 +00003123** Seek to the offset passed as the second argument, then read cnt
3124** bytes into pBuf. Return the number of bytes actually read.
3125**
3126** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3127** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3128** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003129** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003130** See tickets #2741 and #2681.
3131**
3132** To avoid stomping the errno value on a failed read the lastErrno value
3133** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003134*/
drh734c9862008-11-28 15:37:20 +00003135static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3136 int got;
drh58024642011-11-07 18:16:00 +00003137 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003138#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3139 i64 newOffset;
3140#endif
drh734c9862008-11-28 15:37:20 +00003141 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003142 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003143 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003144 do{
drh734c9862008-11-28 15:37:20 +00003145#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003146 got = osPread(id->h, pBuf, cnt, offset);
3147 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003148#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003149 got = osPread64(id->h, pBuf, cnt, offset);
3150 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003151#else
drha46cadc2016-03-04 03:02:06 +00003152 newOffset = lseek(id->h, offset, SEEK_SET);
3153 SimulateIOError( newOffset = -1 );
3154 if( newOffset<0 ){
3155 storeLastErrno((unixFile*)id, errno);
3156 return -1;
3157 }
3158 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003159#endif
drh58024642011-11-07 18:16:00 +00003160 if( got==cnt ) break;
3161 if( got<0 ){
3162 if( errno==EINTR ){ got = 1; continue; }
3163 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003164 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003165 break;
3166 }else if( got>0 ){
3167 cnt -= got;
3168 offset += got;
3169 prior += got;
3170 pBuf = (void*)(got + (char*)pBuf);
3171 }
3172 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003173 TIMER_END;
drh58024642011-11-07 18:16:00 +00003174 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3175 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3176 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003177}
3178
3179/*
drh734c9862008-11-28 15:37:20 +00003180** Read data from a file into a buffer. Return SQLITE_OK if all
3181** bytes were read successfully and SQLITE_IOERR if anything goes
3182** wrong.
drh339eb0b2008-03-07 15:34:11 +00003183*/
drh734c9862008-11-28 15:37:20 +00003184static int unixRead(
3185 sqlite3_file *id,
3186 void *pBuf,
3187 int amt,
3188 sqlite3_int64 offset
3189){
dan08da86a2009-08-21 17:18:03 +00003190 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003191 int got;
3192 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003193 assert( offset>=0 );
3194 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003195
dan08da86a2009-08-21 17:18:03 +00003196 /* If this is a database file (not a journal, master-journal or temp
3197 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003198#if 0
dane946c392009-08-22 11:39:46 +00003199 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003200 || offset>=PENDING_BYTE+512
3201 || offset+amt<=PENDING_BYTE
3202 );
dan7c246102010-04-12 19:00:29 +00003203#endif
drh08c6d442009-02-09 17:34:07 +00003204
drh9b4c59f2013-04-15 17:03:42 +00003205#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003206 /* Deal with as much of this read request as possible by transfering
3207 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003208 if( offset<pFile->mmapSize ){
3209 if( offset+amt <= pFile->mmapSize ){
3210 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3211 return SQLITE_OK;
3212 }else{
3213 int nCopy = pFile->mmapSize - offset;
3214 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3215 pBuf = &((u8 *)pBuf)[nCopy];
3216 amt -= nCopy;
3217 offset += nCopy;
3218 }
3219 }
drh6e0b6d52013-04-09 16:19:20 +00003220#endif
danf23da962013-03-23 21:00:41 +00003221
dan08da86a2009-08-21 17:18:03 +00003222 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003223 if( got==amt ){
3224 return SQLITE_OK;
3225 }else if( got<0 ){
3226 /* lastErrno set by seekAndRead */
3227 return SQLITE_IOERR_READ;
3228 }else{
drh4bf66fd2015-02-19 02:43:02 +00003229 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003230 /* Unread parts of the buffer must be zero-filled */
3231 memset(&((char*)pBuf)[got], 0, amt-got);
3232 return SQLITE_IOERR_SHORT_READ;
3233 }
3234}
3235
3236/*
dan47a2b4a2013-04-26 16:09:29 +00003237** Attempt to seek the file-descriptor passed as the first argument to
3238** absolute offset iOff, then attempt to write nBuf bytes of data from
3239** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3240** return the actual number of bytes written (which may be less than
3241** nBuf).
3242*/
3243static int seekAndWriteFd(
3244 int fd, /* File descriptor to write to */
3245 i64 iOff, /* File offset to begin writing at */
3246 const void *pBuf, /* Copy data from this buffer to the file */
3247 int nBuf, /* Size of buffer pBuf in bytes */
3248 int *piErrno /* OUT: Error number if error occurs */
3249){
3250 int rc = 0; /* Value returned by system call */
3251
3252 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003253 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003254 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003255 nBuf &= 0x1ffff;
3256 TIMER_START;
3257
3258#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003259 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003260#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003261 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003262#else
3263 do{
3264 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003265 SimulateIOError( iSeek = -1 );
3266 if( iSeek<0 ){
3267 rc = -1;
3268 break;
dan47a2b4a2013-04-26 16:09:29 +00003269 }
3270 rc = osWrite(fd, pBuf, nBuf);
3271 }while( rc<0 && errno==EINTR );
3272#endif
3273
3274 TIMER_END;
3275 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3276
drhe1818ec2015-12-01 16:21:35 +00003277 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003278 return rc;
3279}
3280
3281
3282/*
drh734c9862008-11-28 15:37:20 +00003283** Seek to the offset in id->offset then read cnt bytes into pBuf.
3284** Return the number of bytes actually read. Update the offset.
3285**
3286** To avoid stomping the errno value on a failed write the lastErrno value
3287** is set before returning.
3288*/
3289static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003290 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003291}
3292
3293
3294/*
3295** Write data from a buffer into a file. Return SQLITE_OK on success
3296** or some other error code on failure.
3297*/
3298static int unixWrite(
3299 sqlite3_file *id,
3300 const void *pBuf,
3301 int amt,
3302 sqlite3_int64 offset
3303){
dan08da86a2009-08-21 17:18:03 +00003304 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003305 int wrote = 0;
3306 assert( id );
3307 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003308
dan08da86a2009-08-21 17:18:03 +00003309 /* If this is a database file (not a journal, master-journal or temp
3310 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003311#if 0
dane946c392009-08-22 11:39:46 +00003312 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003313 || offset>=PENDING_BYTE+512
3314 || offset+amt<=PENDING_BYTE
3315 );
dan7c246102010-04-12 19:00:29 +00003316#endif
drh08c6d442009-02-09 17:34:07 +00003317
drhd3d8c042012-05-29 17:02:40 +00003318#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003319 /* If we are doing a normal write to a database file (as opposed to
3320 ** doing a hot-journal rollback or a write to some file other than a
3321 ** normal database file) then record the fact that the database
3322 ** has changed. If the transaction counter is modified, record that
3323 ** fact too.
3324 */
dan08da86a2009-08-21 17:18:03 +00003325 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003326 pFile->dbUpdate = 1; /* The database has been modified */
3327 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003328 int rc;
drh8f941bc2009-01-14 23:03:40 +00003329 char oldCntr[4];
3330 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003331 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003332 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003333 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003334 pFile->transCntrChng = 1; /* The transaction counter has changed */
3335 }
3336 }
3337 }
3338#endif
3339
danfe33e392015-11-17 20:56:06 +00003340#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003341 /* Deal with as much of this write request as possible by transfering
3342 ** data from the memory mapping using memcpy(). */
3343 if( offset<pFile->mmapSize ){
3344 if( offset+amt <= pFile->mmapSize ){
3345 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3346 return SQLITE_OK;
3347 }else{
3348 int nCopy = pFile->mmapSize - offset;
3349 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3350 pBuf = &((u8 *)pBuf)[nCopy];
3351 amt -= nCopy;
3352 offset += nCopy;
3353 }
3354 }
drh6e0b6d52013-04-09 16:19:20 +00003355#endif
drh02bf8b42015-09-01 23:51:53 +00003356
3357 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003358 amt -= wrote;
3359 offset += wrote;
3360 pBuf = &((char*)pBuf)[wrote];
3361 }
3362 SimulateIOError(( wrote=(-1), amt=1 ));
3363 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003364
drh02bf8b42015-09-01 23:51:53 +00003365 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003366 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003367 /* lastErrno set by seekAndWrite */
3368 return SQLITE_IOERR_WRITE;
3369 }else{
drh4bf66fd2015-02-19 02:43:02 +00003370 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003371 return SQLITE_FULL;
3372 }
3373 }
dan6e09d692010-07-27 18:34:15 +00003374
drh734c9862008-11-28 15:37:20 +00003375 return SQLITE_OK;
3376}
3377
3378#ifdef SQLITE_TEST
3379/*
3380** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003381** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003382*/
3383int sqlite3_sync_count = 0;
3384int sqlite3_fullsync_count = 0;
3385#endif
3386
3387/*
drh89240432009-03-25 01:06:01 +00003388** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003389** Others do no. To be safe, we will stick with the (slightly slower)
3390** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003391** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003392*/
drhf7a4a1b2015-01-10 18:02:45 +00003393#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003394# define fdatasync fsync
3395#endif
3396
3397/*
3398** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3399** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3400** only available on Mac OS X. But that could change.
3401*/
3402#ifdef F_FULLFSYNC
3403# define HAVE_FULLFSYNC 1
3404#else
3405# define HAVE_FULLFSYNC 0
3406#endif
3407
3408
3409/*
3410** The fsync() system call does not work as advertised on many
3411** unix systems. The following procedure is an attempt to make
3412** it work better.
3413**
3414** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3415** for testing when we want to run through the test suite quickly.
3416** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3417** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3418** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003419**
3420** SQLite sets the dataOnly flag if the size of the file is unchanged.
3421** The idea behind dataOnly is that it should only write the file content
3422** to disk, not the inode. We only set dataOnly if the file size is
3423** unchanged since the file size is part of the inode. However,
3424** Ted Ts'o tells us that fdatasync() will also write the inode if the
3425** file size has changed. The only real difference between fdatasync()
3426** and fsync(), Ted tells us, is that fdatasync() will not flush the
3427** inode if the mtime or owner or other inode attributes have changed.
3428** We only care about the file size, not the other file attributes, so
3429** as far as SQLite is concerned, an fdatasync() is always adequate.
3430** So, we always use fdatasync() if it is available, regardless of
3431** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003432*/
3433static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003434 int rc;
drh734c9862008-11-28 15:37:20 +00003435
3436 /* The following "ifdef/elif/else/" block has the same structure as
3437 ** the one below. It is replicated here solely to avoid cluttering
3438 ** up the real code with the UNUSED_PARAMETER() macros.
3439 */
3440#ifdef SQLITE_NO_SYNC
3441 UNUSED_PARAMETER(fd);
3442 UNUSED_PARAMETER(fullSync);
3443 UNUSED_PARAMETER(dataOnly);
3444#elif HAVE_FULLFSYNC
3445 UNUSED_PARAMETER(dataOnly);
3446#else
3447 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003448 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003449#endif
3450
3451 /* Record the number of times that we do a normal fsync() and
3452 ** FULLSYNC. This is used during testing to verify that this procedure
3453 ** gets called with the correct arguments.
3454 */
3455#ifdef SQLITE_TEST
3456 if( fullSync ) sqlite3_fullsync_count++;
3457 sqlite3_sync_count++;
3458#endif
3459
3460 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003461 ** no-op. But go ahead and call fstat() to validate the file
3462 ** descriptor as we need a method to provoke a failure during
3463 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003464 */
3465#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003466 {
3467 struct stat buf;
3468 rc = osFstat(fd, &buf);
3469 }
drh734c9862008-11-28 15:37:20 +00003470#elif HAVE_FULLFSYNC
3471 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003472 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003473 }else{
3474 rc = 1;
3475 }
3476 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003477 ** It shouldn't be possible for fullfsync to fail on the local
3478 ** file system (on OSX), so failure indicates that FULLFSYNC
3479 ** isn't supported for this file system. So, attempt an fsync
3480 ** and (for now) ignore the overhead of a superfluous fcntl call.
3481 ** It'd be better to detect fullfsync support once and avoid
3482 ** the fcntl call every time sync is called.
3483 */
drh734c9862008-11-28 15:37:20 +00003484 if( rc ) rc = fsync(fd);
3485
drh7ed97b92010-01-20 13:07:21 +00003486#elif defined(__APPLE__)
3487 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3488 ** so currently we default to the macro that redefines fdatasync to fsync
3489 */
3490 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003491#else
drh0b647ff2009-03-21 14:41:04 +00003492 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003493#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003494 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003495 rc = fsync(fd);
3496 }
drh0b647ff2009-03-21 14:41:04 +00003497#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003498#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3499
3500 if( OS_VXWORKS && rc!= -1 ){
3501 rc = 0;
3502 }
chw97185482008-11-17 08:05:31 +00003503 return rc;
drhbfe66312006-10-03 17:40:40 +00003504}
3505
drh734c9862008-11-28 15:37:20 +00003506/*
drh0059eae2011-08-08 23:48:40 +00003507** Open a file descriptor to the directory containing file zFilename.
3508** If successful, *pFd is set to the opened file descriptor and
3509** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3510** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3511** value.
3512**
drh90315a22011-08-10 01:52:12 +00003513** The directory file descriptor is used for only one thing - to
3514** fsync() a directory to make sure file creation and deletion events
3515** are flushed to disk. Such fsyncs are not needed on newer
3516** journaling filesystems, but are required on older filesystems.
3517**
3518** This routine can be overridden using the xSetSysCall interface.
3519** The ability to override this routine was added in support of the
3520** chromium sandbox. Opening a directory is a security risk (we are
3521** told) so making it overrideable allows the chromium sandbox to
3522** replace this routine with a harmless no-op. To make this routine
3523** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3524** *pFd set to a negative number.
3525**
drh0059eae2011-08-08 23:48:40 +00003526** If SQLITE_OK is returned, the caller is responsible for closing
3527** the file descriptor *pFd using close().
3528*/
3529static int openDirectory(const char *zFilename, int *pFd){
3530 int ii;
3531 int fd = -1;
3532 char zDirname[MAX_PATHNAME+1];
3533
3534 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003535 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3536 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003537 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003538 }else{
3539 if( zDirname[0]!='/' ) zDirname[0] = '.';
3540 zDirname[1] = 0;
3541 }
3542 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3543 if( fd>=0 ){
3544 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003545 }
3546 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003547 if( fd>=0 ) return SQLITE_OK;
3548 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003549}
3550
3551/*
drh734c9862008-11-28 15:37:20 +00003552** Make sure all writes to a particular file are committed to disk.
3553**
3554** If dataOnly==0 then both the file itself and its metadata (file
3555** size, access time, etc) are synced. If dataOnly!=0 then only the
3556** file data is synced.
3557**
3558** Under Unix, also make sure that the directory entry for the file
3559** has been created by fsync-ing the directory that contains the file.
3560** If we do not do this and we encounter a power failure, the directory
3561** entry for the journal might not exist after we reboot. The next
3562** SQLite to access the file will not know that the journal exists (because
3563** the directory entry for the journal was never created) and the transaction
3564** will not roll back - possibly leading to database corruption.
3565*/
3566static int unixSync(sqlite3_file *id, int flags){
3567 int rc;
3568 unixFile *pFile = (unixFile*)id;
3569
3570 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3571 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3572
3573 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3574 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3575 || (flags&0x0F)==SQLITE_SYNC_FULL
3576 );
3577
3578 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3579 ** line is to test that doing so does not cause any problems.
3580 */
3581 SimulateDiskfullError( return SQLITE_FULL );
3582
3583 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003584 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003585 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3586 SimulateIOError( rc=1 );
3587 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003588 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003589 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003590 }
drh0059eae2011-08-08 23:48:40 +00003591
3592 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003593 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003594 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003595 */
3596 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3597 int dirfd;
3598 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003599 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003600 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003601 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003602 full_fsync(dirfd, 0, 0);
3603 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003604 }else{
3605 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003606 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003607 }
drh0059eae2011-08-08 23:48:40 +00003608 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003609 }
3610 return rc;
3611}
3612
3613/*
3614** Truncate an open file to a specified size
3615*/
3616static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003617 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003618 int rc;
dan6e09d692010-07-27 18:34:15 +00003619 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003620 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003621
3622 /* If the user has configured a chunk-size for this file, truncate the
3623 ** file so that it consists of an integer number of chunks (i.e. the
3624 ** actual file size after the operation may be larger than the requested
3625 ** size).
3626 */
drhb8af4b72012-04-05 20:04:39 +00003627 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003628 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3629 }
3630
dan2ee53412014-09-06 16:49:40 +00003631 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003632 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003633 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003634 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003635 }else{
drhd3d8c042012-05-29 17:02:40 +00003636#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003637 /* If we are doing a normal write to a database file (as opposed to
3638 ** doing a hot-journal rollback or a write to some file other than a
3639 ** normal database file) and we truncate the file to zero length,
3640 ** that effectively updates the change counter. This might happen
3641 ** when restoring a database using the backup API from a zero-length
3642 ** source.
3643 */
dan6e09d692010-07-27 18:34:15 +00003644 if( pFile->inNormalWrite && nByte==0 ){
3645 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003646 }
danf23da962013-03-23 21:00:41 +00003647#endif
danc0003312013-03-22 17:46:11 +00003648
mistachkine98844f2013-08-24 00:59:24 +00003649#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003650 /* If the file was just truncated to a size smaller than the currently
3651 ** mapped region, reduce the effective mapping size as well. SQLite will
3652 ** use read() and write() to access data beyond this point from now on.
3653 */
3654 if( nByte<pFile->mmapSize ){
3655 pFile->mmapSize = nByte;
3656 }
mistachkine98844f2013-08-24 00:59:24 +00003657#endif
drh3313b142009-11-06 04:13:18 +00003658
drh734c9862008-11-28 15:37:20 +00003659 return SQLITE_OK;
3660 }
3661}
3662
3663/*
3664** Determine the current size of a file in bytes
3665*/
3666static int unixFileSize(sqlite3_file *id, i64 *pSize){
3667 int rc;
3668 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003669 assert( id );
3670 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003671 SimulateIOError( rc=1 );
3672 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003673 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003674 return SQLITE_IOERR_FSTAT;
3675 }
3676 *pSize = buf.st_size;
3677
drh8af6c222010-05-14 12:43:01 +00003678 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003679 ** writes a single byte into that file in order to work around a bug
3680 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3681 ** layers, we need to report this file size as zero even though it is
3682 ** really 1. Ticket #3260.
3683 */
3684 if( *pSize==1 ) *pSize = 0;
3685
3686
3687 return SQLITE_OK;
3688}
3689
drhd2cb50b2009-01-09 21:41:17 +00003690#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003691/*
3692** Handler for proxy-locking file-control verbs. Defined below in the
3693** proxying locking division.
3694*/
3695static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003696#endif
drh715ff302008-12-03 22:32:44 +00003697
dan502019c2010-07-28 14:26:17 +00003698/*
3699** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003700** file-control operation. Enlarge the database to nBytes in size
3701** (rounded up to the next chunk-size). If the database is already
3702** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003703*/
3704static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003705 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003706 i64 nSize; /* Required file size */
3707 struct stat buf; /* Used to hold return values of fstat() */
3708
drh4bf66fd2015-02-19 02:43:02 +00003709 if( osFstat(pFile->h, &buf) ){
3710 return SQLITE_IOERR_FSTAT;
3711 }
dan502019c2010-07-28 14:26:17 +00003712
3713 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3714 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003715
dan502019c2010-07-28 14:26:17 +00003716#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003717 /* The code below is handling the return value of osFallocate()
3718 ** correctly. posix_fallocate() is defined to "returns zero on success,
3719 ** or an error number on failure". See the manpage for details. */
3720 int err;
drhff812312011-02-23 13:33:46 +00003721 do{
dan661d71a2011-03-30 19:08:03 +00003722 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3723 }while( err==EINTR );
3724 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003725#else
dan592bf7f2014-12-30 19:58:31 +00003726 /* If the OS does not have posix_fallocate(), fake it. Write a
3727 ** single byte to the last byte in each block that falls entirely
3728 ** within the extended region. Then, if required, a single byte
3729 ** at offset (nSize-1), to set the size of the file correctly.
3730 ** This is a similar technique to that used by glibc on systems
3731 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003732 */
3733 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003734 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003735 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003736
drh053378d2015-12-01 22:09:42 +00003737 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003738 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003739 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003740 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3741 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003742 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003743 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003744 }
dan502019c2010-07-28 14:26:17 +00003745#endif
3746 }
3747 }
3748
mistachkine98844f2013-08-24 00:59:24 +00003749#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003750 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003751 int rc;
3752 if( pFile->szChunk<=0 ){
3753 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003754 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003755 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3756 }
3757 }
3758
3759 rc = unixMapfile(pFile, nByte);
3760 return rc;
3761 }
mistachkine98844f2013-08-24 00:59:24 +00003762#endif
danf23da962013-03-23 21:00:41 +00003763
dan502019c2010-07-28 14:26:17 +00003764 return SQLITE_OK;
3765}
danielk1977ad94b582007-08-20 06:44:22 +00003766
danielk1977e3026632004-06-22 11:29:02 +00003767/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003768** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003769** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3770**
3771** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3772*/
3773static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3774 if( *pArg<0 ){
3775 *pArg = (pFile->ctrlFlags & mask)!=0;
3776 }else if( (*pArg)==0 ){
3777 pFile->ctrlFlags &= ~mask;
3778 }else{
3779 pFile->ctrlFlags |= mask;
3780 }
3781}
3782
drh696b33e2012-12-06 19:01:42 +00003783/* Forward declaration */
3784static int unixGetTempname(int nBuf, char *zBuf);
3785
drhf12b3f62011-12-21 14:42:29 +00003786/*
drh9e33c2c2007-08-31 18:34:59 +00003787** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003788*/
drhcc6bb3e2007-08-31 16:11:35 +00003789static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003790 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003791 switch( op ){
danefe16972017-07-20 19:49:14 +00003792 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3793 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
3794 return rc ? SQLITE_ERROR : SQLITE_OK;
3795 }
3796 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3797 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
3798 return rc ? SQLITE_ERROR : SQLITE_OK;
3799 }
3800 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3801 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
3802 return rc ? SQLITE_ERROR : SQLITE_OK;
3803 }
3804
drh9e33c2c2007-08-31 18:34:59 +00003805 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003806 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003807 return SQLITE_OK;
3808 }
drh4bf66fd2015-02-19 02:43:02 +00003809 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003810 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003811 return SQLITE_OK;
3812 }
dan6e09d692010-07-27 18:34:15 +00003813 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003814 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003815 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003816 }
drh9ff27ec2010-05-19 19:26:05 +00003817 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003818 int rc;
3819 SimulateIOErrorBenign(1);
3820 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3821 SimulateIOErrorBenign(0);
3822 return rc;
drhf0b190d2011-07-26 16:03:07 +00003823 }
3824 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003825 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3826 return SQLITE_OK;
3827 }
drhcb15f352011-12-23 01:04:17 +00003828 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3829 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003830 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003831 }
drhde60fc22011-12-14 17:53:36 +00003832 case SQLITE_FCNTL_VFSNAME: {
3833 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3834 return SQLITE_OK;
3835 }
drh696b33e2012-12-06 19:01:42 +00003836 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003837 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003838 if( zTFile ){
3839 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3840 *(char**)pArg = zTFile;
3841 }
3842 return SQLITE_OK;
3843 }
drhb959a012013-12-07 12:29:22 +00003844 case SQLITE_FCNTL_HAS_MOVED: {
3845 *(int*)pArg = fileHasMoved(pFile);
3846 return SQLITE_OK;
3847 }
mistachkine98844f2013-08-24 00:59:24 +00003848#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003849 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003850 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003851 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003852 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3853 newLimit = sqlite3GlobalConfig.mxMmap;
3854 }
3855 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003856 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003857 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003858 if( pFile->mmapSize>0 ){
3859 unixUnmapfile(pFile);
3860 rc = unixMapfile(pFile, -1);
3861 }
danbcb8a862013-04-08 15:30:41 +00003862 }
drh34e258c2013-05-23 01:40:53 +00003863 return rc;
danb2d3de32013-03-14 18:34:37 +00003864 }
mistachkine98844f2013-08-24 00:59:24 +00003865#endif
drhd3d8c042012-05-29 17:02:40 +00003866#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003867 /* The pager calls this method to signal that it has done
3868 ** a rollback and that the database is therefore unchanged and
3869 ** it hence it is OK for the transaction change counter to be
3870 ** unchanged.
3871 */
3872 case SQLITE_FCNTL_DB_UNCHANGED: {
3873 ((unixFile*)id)->dbUpdate = 0;
3874 return SQLITE_OK;
3875 }
3876#endif
drhd2cb50b2009-01-09 21:41:17 +00003877#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003878 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3879 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003880 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003881 }
drhd2cb50b2009-01-09 21:41:17 +00003882#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003883 }
drh0b52b7d2011-01-26 19:46:22 +00003884 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003885}
3886
3887/*
danefe16972017-07-20 19:49:14 +00003888** If pFd->sectorSize is non-zero when this function is called, it is a
3889** no-op. Otherwise, the values of pFd->sectorSize and
3890** pFd->deviceCharacteristics are set according to the file-system
3891** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00003892**
danefe16972017-07-20 19:49:14 +00003893** There are two versions of this function. One for QNX and one for all
3894** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00003895*/
danefe16972017-07-20 19:49:14 +00003896#ifndef __QNXNTO__
3897static void setDeviceCharacteristics(unixFile *pFd){
3898 if( pFd->sectorSize==0 ){
3899 int res;
dan9d709542017-07-21 21:06:24 +00003900 u32 f = 0;
danefe16972017-07-20 19:49:14 +00003901 assert( pFd->deviceCharacteristics==0 );
drh537dddf2012-10-26 13:46:24 +00003902
danefe16972017-07-20 19:49:14 +00003903 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00003904 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
3905 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
danefe16972017-07-20 19:49:14 +00003906 pFd->deviceCharacteristics =
3907 SQLITE_IOCAP_BATCH_ATOMIC |
3908 SQLITE_IOCAP_ATOMIC |
3909 SQLITE_IOCAP_SEQUENTIAL |
3910 SQLITE_IOCAP_SAFE_APPEND;
3911 }
3912
3913 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3914 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3915 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3916 }
3917
3918 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3919 }
3920}
3921#else
drh537dddf2012-10-26 13:46:24 +00003922#include <sys/dcmd_blk.h>
3923#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00003924static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00003925 if( pFile->sectorSize == 0 ){
3926 struct statvfs fsInfo;
3927
3928 /* Set defaults for non-supported filesystems */
3929 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3930 pFile->deviceCharacteristics = 0;
3931 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3932 return pFile->sectorSize;
3933 }
3934
3935 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3936 pFile->sectorSize = fsInfo.f_bsize;
3937 pFile->deviceCharacteristics =
3938 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3939 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3940 ** the write succeeds */
3941 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3942 ** so it is ordered */
3943 0;
3944 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3945 pFile->sectorSize = fsInfo.f_bsize;
3946 pFile->deviceCharacteristics =
3947 /* etfs cluster size writes are atomic */
3948 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3949 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3950 ** the write succeeds */
3951 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3952 ** so it is ordered */
3953 0;
3954 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3955 pFile->sectorSize = fsInfo.f_bsize;
3956 pFile->deviceCharacteristics =
3957 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3958 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3959 ** the write succeeds */
3960 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3961 ** so it is ordered */
3962 0;
3963 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3964 pFile->sectorSize = fsInfo.f_bsize;
3965 pFile->deviceCharacteristics =
3966 /* full bitset of atomics from max sector size and smaller */
3967 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3968 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3969 ** so it is ordered */
3970 0;
3971 }else if( strstr(fsInfo.f_basetype, "dos") ){
3972 pFile->sectorSize = fsInfo.f_bsize;
3973 pFile->deviceCharacteristics =
3974 /* full bitset of atomics from max sector size and smaller */
3975 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3976 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3977 ** so it is ordered */
3978 0;
3979 }else{
3980 pFile->deviceCharacteristics =
3981 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3982 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3983 ** the write succeeds */
3984 0;
3985 }
3986 }
3987 /* Last chance verification. If the sector size isn't a multiple of 512
3988 ** then it isn't valid.*/
3989 if( pFile->sectorSize % 512 != 0 ){
3990 pFile->deviceCharacteristics = 0;
3991 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3992 }
drh537dddf2012-10-26 13:46:24 +00003993}
danefe16972017-07-20 19:49:14 +00003994#endif
3995
3996/*
3997** Return the sector size in bytes of the underlying block device for
3998** the specified file. This is almost always 512 bytes, but may be
3999** larger for some devices.
4000**
4001** SQLite code assumes this function cannot fail. It also assumes that
4002** if two files are created in the same file-system directory (i.e.
4003** a database and its journal file) that the sector size will be the
4004** same for both.
4005*/
4006static int unixSectorSize(sqlite3_file *id){
4007 unixFile *pFd = (unixFile*)id;
4008 setDeviceCharacteristics(pFd);
4009 return pFd->sectorSize;
4010}
danielk1977a3d4c882007-03-23 10:08:38 +00004011
danielk197790949c22007-08-17 16:50:38 +00004012/*
drhf12b3f62011-12-21 14:42:29 +00004013** Return the device characteristics for the file.
4014**
drhcb15f352011-12-23 01:04:17 +00004015** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004016** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004017** file system does not always provide powersafe overwrites. (In other
4018** words, after a power-loss event, parts of the file that were never
4019** written might end up being altered.) However, non-PSOW behavior is very,
4020** very rare. And asserting PSOW makes a large reduction in the amount
4021** of required I/O for journaling, since a lot of padding is eliminated.
4022** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4023** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004024*/
drhf12b3f62011-12-21 14:42:29 +00004025static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004026 unixFile *pFd = (unixFile*)id;
4027 setDeviceCharacteristics(pFd);
4028 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004029}
4030
dan702eec12014-06-23 10:04:58 +00004031#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004032
dan702eec12014-06-23 10:04:58 +00004033/*
4034** Return the system page size.
4035**
4036** This function should not be called directly by other code in this file.
4037** Instead, it should be called via macro osGetpagesize().
4038*/
4039static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004040#if OS_VXWORKS
4041 return 1024;
4042#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004043 return getpagesize();
4044#else
4045 return (int)sysconf(_SC_PAGESIZE);
4046#endif
4047}
4048
4049#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4050
4051#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004052
4053/*
drhd91c68f2010-05-14 14:52:25 +00004054** Object used to represent an shared memory buffer.
4055**
4056** When multiple threads all reference the same wal-index, each thread
4057** has its own unixShm object, but they all point to a single instance
4058** of this unixShmNode object. In other words, each wal-index is opened
4059** only once per process.
4060**
4061** Each unixShmNode object is connected to a single unixInodeInfo object.
4062** We could coalesce this object into unixInodeInfo, but that would mean
4063** every open file that does not use shared memory (in other words, most
4064** open files) would have to carry around this extra information. So
4065** the unixInodeInfo object contains a pointer to this unixShmNode object
4066** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004067**
4068** unixMutexHeld() must be true when creating or destroying
4069** this object or while reading or writing the following fields:
4070**
4071** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004072**
4073** The following fields are read-only after the object is created:
4074**
4075** fid
4076** zFilename
4077**
drhd91c68f2010-05-14 14:52:25 +00004078** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004079** unixMutexHeld() is true when reading or writing any other field
4080** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004081*/
drhd91c68f2010-05-14 14:52:25 +00004082struct unixShmNode {
4083 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004084 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004085 char *zFilename; /* Name of the mmapped file */
4086 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004087 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004088 u16 nRegion; /* Size of array apRegion */
4089 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004090 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004091 int nRef; /* Number of unixShm objects pointing to this */
4092 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004093#ifdef SQLITE_DEBUG
4094 u8 exclMask; /* Mask of exclusive locks held */
4095 u8 sharedMask; /* Mask of shared locks held */
4096 u8 nextShmId; /* Next available unixShm.id value */
4097#endif
4098};
4099
4100/*
drhd9e5c4f2010-05-12 18:01:39 +00004101** Structure used internally by this VFS to record the state of an
4102** open shared memory connection.
4103**
drhd91c68f2010-05-14 14:52:25 +00004104** The following fields are initialized when this object is created and
4105** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004106**
drhd91c68f2010-05-14 14:52:25 +00004107** unixShm.pFile
4108** unixShm.id
4109**
4110** All other fields are read/write. The unixShm.pFile->mutex must be held
4111** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004112*/
4113struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004114 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4115 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004116 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004117 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004118 u16 sharedMask; /* Mask of shared locks held */
4119 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004120};
4121
4122/*
drhd9e5c4f2010-05-12 18:01:39 +00004123** Constants used for locking
4124*/
drhbd9676c2010-06-23 17:58:38 +00004125#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004126#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004127
drhd9e5c4f2010-05-12 18:01:39 +00004128/*
drh73b64e42010-05-30 19:55:15 +00004129** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004130**
4131** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4132** otherwise.
4133*/
4134static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004135 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004136 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004137 int ofst, /* First byte of the locking range */
4138 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004139){
drhbbf76ee2015-03-10 20:22:35 +00004140 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4141 struct flock f; /* The posix advisory locking structure */
4142 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004143
drhd91c68f2010-05-14 14:52:25 +00004144 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004145 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004146 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004147
drh73b64e42010-05-30 19:55:15 +00004148 /* Shared locks never span more than one byte */
4149 assert( n==1 || lockType!=F_RDLCK );
4150
4151 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004152 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004153
drh3cb93392011-03-12 18:10:44 +00004154 if( pShmNode->h>=0 ){
4155 /* Initialize the locking parameters */
4156 memset(&f, 0, sizeof(f));
4157 f.l_type = lockType;
4158 f.l_whence = SEEK_SET;
4159 f.l_start = ofst;
4160 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004161
drhdcfb9652015-12-02 00:05:26 +00004162 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004163 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4164 }
drhd9e5c4f2010-05-12 18:01:39 +00004165
4166 /* Update the global lock state and do debug tracing */
4167#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004168 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004169 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004170 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004171 if( rc==SQLITE_OK ){
4172 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004173 OSTRACE(("unlock %d ok", ofst));
4174 pShmNode->exclMask &= ~mask;
4175 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004176 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004177 OSTRACE(("read-lock %d ok", ofst));
4178 pShmNode->exclMask &= ~mask;
4179 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004180 }else{
4181 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004182 OSTRACE(("write-lock %d ok", ofst));
4183 pShmNode->exclMask |= mask;
4184 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004185 }
4186 }else{
4187 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004188 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004189 }else if( lockType==F_RDLCK ){
4190 OSTRACE(("read-lock failed"));
4191 }else{
4192 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004193 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004194 }
4195 }
drh20e1f082010-05-31 16:10:12 +00004196 OSTRACE((" - afterwards %03x,%03x\n",
4197 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004198 }
drhd9e5c4f2010-05-12 18:01:39 +00004199#endif
4200
4201 return rc;
4202}
4203
dan781e34c2014-03-20 08:59:47 +00004204/*
dan781e34c2014-03-20 08:59:47 +00004205** Return the minimum number of 32KB shm regions that should be mapped at
4206** a time, assuming that each mapping must be an integer multiple of the
4207** current system page-size.
4208**
4209** Usually, this is 1. The exception seems to be systems that are configured
4210** to use 64KB pages - in this case each mapping must cover at least two
4211** shm regions.
4212*/
4213static int unixShmRegionPerMap(void){
4214 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004215 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004216 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4217 if( pgsz<shmsz ) return 1;
4218 return pgsz/shmsz;
4219}
drhd9e5c4f2010-05-12 18:01:39 +00004220
4221/*
drhd91c68f2010-05-14 14:52:25 +00004222** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004223**
4224** This is not a VFS shared-memory method; it is a utility function called
4225** by VFS shared-memory methods.
4226*/
drhd91c68f2010-05-14 14:52:25 +00004227static void unixShmPurge(unixFile *pFd){
4228 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004229 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004230 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004231 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004232 int i;
drhd91c68f2010-05-14 14:52:25 +00004233 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004234 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004235 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004236 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004237 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004238 }else{
4239 sqlite3_free(p->apRegion[i]);
4240 }
dan13a3cb82010-06-11 19:04:21 +00004241 }
dan18801912010-06-14 14:07:50 +00004242 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004243 if( p->h>=0 ){
4244 robust_close(pFd, p->h, __LINE__);
4245 p->h = -1;
4246 }
drhd91c68f2010-05-14 14:52:25 +00004247 p->pInode->pShmNode = 0;
4248 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004249 }
4250}
4251
4252/*
danda9fe0c2010-07-13 18:44:03 +00004253** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004254** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004255**
drh7234c6d2010-06-19 15:10:09 +00004256** The file used to implement shared-memory is in the same directory
4257** as the open database file and has the same name as the open database
4258** file with the "-shm" suffix added. For example, if the database file
4259** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004260** for shared memory will be called "/home/user1/config.db-shm".
4261**
4262** Another approach to is to use files in /dev/shm or /dev/tmp or an
4263** some other tmpfs mount. But if a file in a different directory
4264** from the database file is used, then differing access permissions
4265** or a chroot() might cause two different processes on the same
4266** database to end up using different files for shared memory -
4267** meaning that their memory would not really be shared - resulting
4268** in database corruption. Nevertheless, this tmpfs file usage
4269** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4270** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4271** option results in an incompatible build of SQLite; builds of SQLite
4272** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4273** same database file at the same time, database corruption will likely
4274** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4275** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004276**
4277** When opening a new shared-memory file, if no other instances of that
4278** file are currently open, in this process or in other processes, then
4279** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004280**
4281** If the original database file (pDbFd) is using the "unix-excl" VFS
4282** that means that an exclusive lock is held on the database file and
4283** that no other processes are able to read or write the database. In
4284** that case, we do not really need shared memory. No shared memory
4285** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004286*/
danda9fe0c2010-07-13 18:44:03 +00004287static int unixOpenSharedMemory(unixFile *pDbFd){
4288 struct unixShm *p = 0; /* The connection to be opened */
4289 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4290 int rc; /* Result code */
4291 unixInodeInfo *pInode; /* The inode of fd */
4292 char *zShmFilename; /* Name of the file used for SHM */
4293 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004294
danda9fe0c2010-07-13 18:44:03 +00004295 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004296 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004297 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004298 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004299 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004300
danda9fe0c2010-07-13 18:44:03 +00004301 /* Check to see if a unixShmNode object already exists. Reuse an existing
4302 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004303 */
4304 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004305 pInode = pDbFd->pInode;
4306 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004307 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004308 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004309#ifndef SQLITE_SHM_DIRECTORY
4310 const char *zBasePath = pDbFd->zPath;
4311#endif
danddb0ac42010-07-14 14:48:58 +00004312
4313 /* Call fstat() to figure out the permissions on the database file. If
4314 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004315 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004316 */
drhf3b1ed02015-12-02 13:11:03 +00004317 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004318 rc = SQLITE_IOERR_FSTAT;
4319 goto shm_open_err;
4320 }
4321
drha4ced192010-07-15 18:32:40 +00004322#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004323 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004324#else
drh4bf66fd2015-02-19 02:43:02 +00004325 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004326#endif
drhf3cdcdc2015-04-29 16:50:28 +00004327 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004328 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004329 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004330 goto shm_open_err;
4331 }
drh9cb5a0d2012-01-05 21:19:54 +00004332 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004333 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004334#ifdef SQLITE_SHM_DIRECTORY
4335 sqlite3_snprintf(nShmFilename, zShmFilename,
4336 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4337 (u32)sStat.st_ino, (u32)sStat.st_dev);
4338#else
drh4bf66fd2015-02-19 02:43:02 +00004339 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004340 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004341#endif
drhd91c68f2010-05-14 14:52:25 +00004342 pShmNode->h = -1;
4343 pDbFd->pInode->pShmNode = pShmNode;
4344 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004345 if( sqlite3GlobalConfig.bCoreMutex ){
4346 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4347 if( pShmNode->mutex==0 ){
4348 rc = SQLITE_NOMEM_BKPT;
4349 goto shm_open_err;
4350 }
drhd91c68f2010-05-14 14:52:25 +00004351 }
drhd9e5c4f2010-05-12 18:01:39 +00004352
drh3cb93392011-03-12 18:10:44 +00004353 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004354 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004355 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004356 openFlags = O_RDONLY;
4357 pShmNode->isReadonly = 1;
4358 }
4359 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004360 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004361 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4362 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004363 }
drhac7c3ac2012-02-11 19:23:48 +00004364
4365 /* If this process is running as root, make sure that the SHM file
4366 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004367 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004368 */
drh6226ca22015-11-24 15:06:28 +00004369 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004370
4371 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004372 ** If not, truncate the file to zero length.
4373 */
4374 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004375 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004376 if( robust_ftruncate(pShmNode->h, 0) ){
4377 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004378 }
4379 }
drh66dfec8b2011-06-01 20:01:49 +00004380 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004381 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004382 }
4383 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004384 }
drhd9e5c4f2010-05-12 18:01:39 +00004385 }
4386
drhd91c68f2010-05-14 14:52:25 +00004387 /* Make the new connection a child of the unixShmNode */
4388 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004389#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004390 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004391#endif
drhd91c68f2010-05-14 14:52:25 +00004392 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004393 pDbFd->pShm = p;
4394 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004395
4396 /* The reference count on pShmNode has already been incremented under
4397 ** the cover of the unixEnterMutex() mutex and the pointer from the
4398 ** new (struct unixShm) object to the pShmNode has been set. All that is
4399 ** left to do is to link the new object into the linked list starting
4400 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4401 ** mutex.
4402 */
4403 sqlite3_mutex_enter(pShmNode->mutex);
4404 p->pNext = pShmNode->pFirst;
4405 pShmNode->pFirst = p;
4406 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004407 return SQLITE_OK;
4408
4409 /* Jump here on any error */
4410shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004411 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004412 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004413 unixLeaveMutex();
4414 return rc;
4415}
4416
4417/*
danda9fe0c2010-07-13 18:44:03 +00004418** This function is called to obtain a pointer to region iRegion of the
4419** shared-memory associated with the database file fd. Shared-memory regions
4420** are numbered starting from zero. Each shared-memory region is szRegion
4421** bytes in size.
4422**
4423** If an error occurs, an error code is returned and *pp is set to NULL.
4424**
4425** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4426** region has not been allocated (by any client, including one running in a
4427** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4428** bExtend is non-zero and the requested shared-memory region has not yet
4429** been allocated, it is allocated by this function.
4430**
4431** If the shared-memory region has already been allocated or is allocated by
4432** this call as described above, then it is mapped into this processes
4433** address space (if it is not already), *pp is set to point to the mapped
4434** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004435*/
danda9fe0c2010-07-13 18:44:03 +00004436static int unixShmMap(
4437 sqlite3_file *fd, /* Handle open on database file */
4438 int iRegion, /* Region to retrieve */
4439 int szRegion, /* Size of regions */
4440 int bExtend, /* True to extend file if necessary */
4441 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004442){
danda9fe0c2010-07-13 18:44:03 +00004443 unixFile *pDbFd = (unixFile*)fd;
4444 unixShm *p;
4445 unixShmNode *pShmNode;
4446 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004447 int nShmPerMap = unixShmRegionPerMap();
4448 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004449
danda9fe0c2010-07-13 18:44:03 +00004450 /* If the shared-memory file has not yet been opened, open it now. */
4451 if( pDbFd->pShm==0 ){
4452 rc = unixOpenSharedMemory(pDbFd);
4453 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004454 }
drhd9e5c4f2010-05-12 18:01:39 +00004455
danda9fe0c2010-07-13 18:44:03 +00004456 p = pDbFd->pShm;
4457 pShmNode = p->pShmNode;
4458 sqlite3_mutex_enter(pShmNode->mutex);
4459 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004460 assert( pShmNode->pInode==pDbFd->pInode );
4461 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4462 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004463
dan781e34c2014-03-20 08:59:47 +00004464 /* Minimum number of regions required to be mapped. */
4465 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4466
4467 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004468 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004469 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004470 struct stat sStat; /* Used by fstat() */
4471
4472 pShmNode->szRegion = szRegion;
4473
drh3cb93392011-03-12 18:10:44 +00004474 if( pShmNode->h>=0 ){
4475 /* The requested region is not mapped into this processes address space.
4476 ** Check to see if it has been allocated (i.e. if the wal-index file is
4477 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004478 */
drh3cb93392011-03-12 18:10:44 +00004479 if( osFstat(pShmNode->h, &sStat) ){
4480 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004481 goto shmpage_out;
4482 }
drh3cb93392011-03-12 18:10:44 +00004483
4484 if( sStat.st_size<nByte ){
4485 /* The requested memory region does not exist. If bExtend is set to
4486 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004487 */
dan47a2b4a2013-04-26 16:09:29 +00004488 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004489 goto shmpage_out;
4490 }
dan47a2b4a2013-04-26 16:09:29 +00004491
4492 /* Alternatively, if bExtend is true, extend the file. Do this by
4493 ** writing a single byte to the end of each (OS) page being
4494 ** allocated or extended. Technically, we need only write to the
4495 ** last page in order to extend the file. But writing to all new
4496 ** pages forces the OS to allocate them immediately, which reduces
4497 ** the chances of SIGBUS while accessing the mapped region later on.
4498 */
4499 else{
4500 static const int pgsz = 4096;
4501 int iPg;
4502
4503 /* Write to the last byte of each newly allocated or extended page */
4504 assert( (nByte % pgsz)==0 );
4505 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004506 int x = 0;
4507 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004508 const char *zFile = pShmNode->zFilename;
4509 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4510 goto shmpage_out;
4511 }
4512 }
drh3cb93392011-03-12 18:10:44 +00004513 }
4514 }
danda9fe0c2010-07-13 18:44:03 +00004515 }
4516
4517 /* Map the requested memory region into this processes address space. */
4518 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004519 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004520 );
4521 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004522 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004523 goto shmpage_out;
4524 }
4525 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004526 while( pShmNode->nRegion<nReqRegion ){
4527 int nMap = szRegion*nShmPerMap;
4528 int i;
drh3cb93392011-03-12 18:10:44 +00004529 void *pMem;
4530 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004531 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004532 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004533 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004534 );
4535 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004536 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004537 goto shmpage_out;
4538 }
4539 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004540 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004541 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004542 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004543 goto shmpage_out;
4544 }
4545 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004546 }
dan781e34c2014-03-20 08:59:47 +00004547
4548 for(i=0; i<nShmPerMap; i++){
4549 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4550 }
4551 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004552 }
4553 }
4554
4555shmpage_out:
4556 if( pShmNode->nRegion>iRegion ){
4557 *pp = pShmNode->apRegion[iRegion];
4558 }else{
4559 *pp = 0;
4560 }
drh66dfec8b2011-06-01 20:01:49 +00004561 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004562 sqlite3_mutex_leave(pShmNode->mutex);
4563 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004564}
4565
4566/*
drhd9e5c4f2010-05-12 18:01:39 +00004567** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004568**
4569** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4570** different here than in posix. In xShmLock(), one can go from unlocked
4571** to shared and back or from unlocked to exclusive and back. But one may
4572** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004573*/
4574static int unixShmLock(
4575 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004576 int ofst, /* First lock to acquire or release */
4577 int n, /* Number of locks to acquire or release */
4578 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004579){
drh73b64e42010-05-30 19:55:15 +00004580 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4581 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4582 unixShm *pX; /* For looping over all siblings */
4583 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4584 int rc = SQLITE_OK; /* Result code */
4585 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004586
drhd91c68f2010-05-14 14:52:25 +00004587 assert( pShmNode==pDbFd->pInode->pShmNode );
4588 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004589 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004590 assert( n>=1 );
4591 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4592 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4593 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4594 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4595 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004596 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4597 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004598
drhc99597c2010-05-31 01:41:15 +00004599 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004600 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004601 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004602 if( flags & SQLITE_SHM_UNLOCK ){
4603 u16 allMask = 0; /* Mask of locks held by siblings */
4604
4605 /* See if any siblings hold this same lock */
4606 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4607 if( pX==p ) continue;
4608 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4609 allMask |= pX->sharedMask;
4610 }
4611
4612 /* Unlock the system-level locks */
4613 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004614 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004615 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004616 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004617 }
drh73b64e42010-05-30 19:55:15 +00004618
4619 /* Undo the local locks */
4620 if( rc==SQLITE_OK ){
4621 p->exclMask &= ~mask;
4622 p->sharedMask &= ~mask;
4623 }
4624 }else if( flags & SQLITE_SHM_SHARED ){
4625 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4626
4627 /* Find out which shared locks are already held by sibling connections.
4628 ** If any sibling already holds an exclusive lock, go ahead and return
4629 ** SQLITE_BUSY.
4630 */
4631 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004632 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004633 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004634 break;
4635 }
4636 allShared |= pX->sharedMask;
4637 }
4638
4639 /* Get shared locks at the system level, if necessary */
4640 if( rc==SQLITE_OK ){
4641 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004642 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004643 }else{
drh73b64e42010-05-30 19:55:15 +00004644 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004645 }
drhd9e5c4f2010-05-12 18:01:39 +00004646 }
drh73b64e42010-05-30 19:55:15 +00004647
4648 /* Get the local shared locks */
4649 if( rc==SQLITE_OK ){
4650 p->sharedMask |= mask;
4651 }
4652 }else{
4653 /* Make sure no sibling connections hold locks that will block this
4654 ** lock. If any do, return SQLITE_BUSY right away.
4655 */
4656 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004657 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4658 rc = SQLITE_BUSY;
4659 break;
4660 }
4661 }
4662
4663 /* Get the exclusive locks at the system level. Then if successful
4664 ** also mark the local connection as being locked.
4665 */
4666 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004667 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004668 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004669 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004670 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004671 }
drhd9e5c4f2010-05-12 18:01:39 +00004672 }
4673 }
drhd91c68f2010-05-14 14:52:25 +00004674 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004675 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004676 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004677 return rc;
4678}
4679
drh286a2882010-05-20 23:51:06 +00004680/*
4681** Implement a memory barrier or memory fence on shared memory.
4682**
4683** All loads and stores begun before the barrier must complete before
4684** any load or store begun after the barrier.
4685*/
4686static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004687 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004688){
drhff828942010-06-26 21:34:06 +00004689 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004690 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4691 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004692 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004693}
4694
dan18801912010-06-14 14:07:50 +00004695/*
danda9fe0c2010-07-13 18:44:03 +00004696** Close a connection to shared-memory. Delete the underlying
4697** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004698**
4699** If there is no shared memory associated with the connection then this
4700** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004701*/
danda9fe0c2010-07-13 18:44:03 +00004702static int unixShmUnmap(
4703 sqlite3_file *fd, /* The underlying database file */
4704 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004705){
danda9fe0c2010-07-13 18:44:03 +00004706 unixShm *p; /* The connection to be closed */
4707 unixShmNode *pShmNode; /* The underlying shared-memory file */
4708 unixShm **pp; /* For looping over sibling connections */
4709 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004710
danda9fe0c2010-07-13 18:44:03 +00004711 pDbFd = (unixFile*)fd;
4712 p = pDbFd->pShm;
4713 if( p==0 ) return SQLITE_OK;
4714 pShmNode = p->pShmNode;
4715
4716 assert( pShmNode==pDbFd->pInode->pShmNode );
4717 assert( pShmNode->pInode==pDbFd->pInode );
4718
4719 /* Remove connection p from the set of connections associated
4720 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004721 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004722 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4723 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004724
danda9fe0c2010-07-13 18:44:03 +00004725 /* Free the connection p */
4726 sqlite3_free(p);
4727 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004728 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004729
4730 /* If pShmNode->nRef has reached 0, then close the underlying
4731 ** shared-memory file, too */
4732 unixEnterMutex();
4733 assert( pShmNode->nRef>0 );
4734 pShmNode->nRef--;
4735 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004736 if( deleteFlag && pShmNode->h>=0 ){
4737 osUnlink(pShmNode->zFilename);
4738 }
danda9fe0c2010-07-13 18:44:03 +00004739 unixShmPurge(pDbFd);
4740 }
4741 unixLeaveMutex();
4742
4743 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004744}
drh286a2882010-05-20 23:51:06 +00004745
danda9fe0c2010-07-13 18:44:03 +00004746
drhd9e5c4f2010-05-12 18:01:39 +00004747#else
drh6b017cc2010-06-14 18:01:46 +00004748# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004749# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004750# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004751# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004752#endif /* #ifndef SQLITE_OMIT_WAL */
4753
mistachkine98844f2013-08-24 00:59:24 +00004754#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004755/*
danaef49d72013-03-25 16:28:54 +00004756** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004757*/
danf23da962013-03-23 21:00:41 +00004758static void unixUnmapfile(unixFile *pFd){
4759 assert( pFd->nFetchOut==0 );
4760 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004761 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004762 pFd->pMapRegion = 0;
4763 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004764 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004765 }
4766}
dan5d8a1372013-03-19 19:28:06 +00004767
danaef49d72013-03-25 16:28:54 +00004768/*
dane6ecd662013-04-01 17:56:59 +00004769** Attempt to set the size of the memory mapping maintained by file
4770** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4771**
4772** If successful, this function sets the following variables:
4773**
4774** unixFile.pMapRegion
4775** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004776** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004777**
4778** If unsuccessful, an error message is logged via sqlite3_log() and
4779** the three variables above are zeroed. In this case SQLite should
4780** continue accessing the database using the xRead() and xWrite()
4781** methods.
4782*/
4783static void unixRemapfile(
4784 unixFile *pFd, /* File descriptor object */
4785 i64 nNew /* Required mapping size */
4786){
dan4ff7bc42013-04-02 12:04:09 +00004787 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004788 int h = pFd->h; /* File descriptor open on db file */
4789 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004790 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004791 u8 *pNew = 0; /* Location of new mapping */
4792 int flags = PROT_READ; /* Flags to pass to mmap() */
4793
4794 assert( pFd->nFetchOut==0 );
4795 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004796 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004797 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004798 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004799 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004800
danfe33e392015-11-17 20:56:06 +00004801#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004802 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004803#endif
dane6ecd662013-04-01 17:56:59 +00004804
4805 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004806#if HAVE_MREMAP
4807 i64 nReuse = pFd->mmapSize;
4808#else
danbc760632014-03-20 09:42:09 +00004809 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004810 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004811#endif
dane6ecd662013-04-01 17:56:59 +00004812 u8 *pReq = &pOrig[nReuse];
4813
4814 /* Unmap any pages of the existing mapping that cannot be reused. */
4815 if( nReuse!=nOrig ){
4816 osMunmap(pReq, nOrig-nReuse);
4817 }
4818
4819#if HAVE_MREMAP
4820 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004821 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004822#else
4823 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4824 if( pNew!=MAP_FAILED ){
4825 if( pNew!=pReq ){
4826 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004827 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004828 }else{
4829 pNew = pOrig;
4830 }
4831 }
4832#endif
4833
dan48ccef82013-04-02 20:55:01 +00004834 /* The attempt to extend the existing mapping failed. Free it. */
4835 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004836 osMunmap(pOrig, nReuse);
4837 }
4838 }
4839
4840 /* If pNew is still NULL, try to create an entirely new mapping. */
4841 if( pNew==0 ){
4842 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004843 }
4844
dan4ff7bc42013-04-02 12:04:09 +00004845 if( pNew==MAP_FAILED ){
4846 pNew = 0;
4847 nNew = 0;
4848 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4849
4850 /* If the mmap() above failed, assume that all subsequent mmap() calls
4851 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4852 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004853 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004854 }
dane6ecd662013-04-01 17:56:59 +00004855 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004856 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004857}
4858
4859/*
danaef49d72013-03-25 16:28:54 +00004860** Memory map or remap the file opened by file-descriptor pFd (if the file
4861** is already mapped, the existing mapping is replaced by the new). Or, if
4862** there already exists a mapping for this file, and there are still
4863** outstanding xFetch() references to it, this function is a no-op.
4864**
4865** If parameter nByte is non-negative, then it is the requested size of
4866** the mapping to create. Otherwise, if nByte is less than zero, then the
4867** requested size is the size of the file on disk. The actual size of the
4868** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004869** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004870**
4871** SQLITE_OK is returned if no error occurs (even if the mapping is not
4872** recreated as a result of outstanding references) or an SQLite error
4873** code otherwise.
4874*/
drhf3b1ed02015-12-02 13:11:03 +00004875static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004876 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004877 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004878 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4879
4880 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004881 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004882 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004883 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004884 }
drh3044b512014-06-16 16:41:52 +00004885 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004886 }
drh9b4c59f2013-04-15 17:03:42 +00004887 if( nMap>pFd->mmapSizeMax ){
4888 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004889 }
4890
drh333e6ca2015-12-02 15:44:39 +00004891 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004892 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004893 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004894 }
4895
danf23da962013-03-23 21:00:41 +00004896 return SQLITE_OK;
4897}
mistachkine98844f2013-08-24 00:59:24 +00004898#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004899
danaef49d72013-03-25 16:28:54 +00004900/*
4901** If possible, return a pointer to a mapping of file fd starting at offset
4902** iOff. The mapping must be valid for at least nAmt bytes.
4903**
4904** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4905** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4906** Finally, if an error does occur, return an SQLite error code. The final
4907** value of *pp is undefined in this case.
4908**
4909** If this function does return a pointer, the caller must eventually
4910** release the reference by calling unixUnfetch().
4911*/
danf23da962013-03-23 21:00:41 +00004912static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004913#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004914 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004915#endif
danf23da962013-03-23 21:00:41 +00004916 *pp = 0;
4917
drh9b4c59f2013-04-15 17:03:42 +00004918#if SQLITE_MAX_MMAP_SIZE>0
4919 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004920 if( pFd->pMapRegion==0 ){
4921 int rc = unixMapfile(pFd, -1);
4922 if( rc!=SQLITE_OK ) return rc;
4923 }
4924 if( pFd->mmapSize >= iOff+nAmt ){
4925 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4926 pFd->nFetchOut++;
4927 }
4928 }
drh6e0b6d52013-04-09 16:19:20 +00004929#endif
danf23da962013-03-23 21:00:41 +00004930 return SQLITE_OK;
4931}
4932
danaef49d72013-03-25 16:28:54 +00004933/*
dandf737fe2013-03-25 17:00:24 +00004934** If the third argument is non-NULL, then this function releases a
4935** reference obtained by an earlier call to unixFetch(). The second
4936** argument passed to this function must be the same as the corresponding
4937** argument that was passed to the unixFetch() invocation.
4938**
4939** Or, if the third argument is NULL, then this function is being called
4940** to inform the VFS layer that, according to POSIX, any existing mapping
4941** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004942*/
dandf737fe2013-03-25 17:00:24 +00004943static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004944#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004945 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004946 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004947
danaef49d72013-03-25 16:28:54 +00004948 /* If p==0 (unmap the entire file) then there must be no outstanding
4949 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4950 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004951 assert( (p==0)==(pFd->nFetchOut==0) );
4952
dandf737fe2013-03-25 17:00:24 +00004953 /* If p!=0, it must match the iOff value. */
4954 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4955
danf23da962013-03-23 21:00:41 +00004956 if( p ){
4957 pFd->nFetchOut--;
4958 }else{
4959 unixUnmapfile(pFd);
4960 }
4961
4962 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004963#else
4964 UNUSED_PARAMETER(fd);
4965 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004966 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004967#endif
danf23da962013-03-23 21:00:41 +00004968 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004969}
4970
4971/*
drh734c9862008-11-28 15:37:20 +00004972** Here ends the implementation of all sqlite3_file methods.
4973**
4974********************** End sqlite3_file Methods *******************************
4975******************************************************************************/
4976
4977/*
drh6b9d6dd2008-12-03 19:34:47 +00004978** This division contains definitions of sqlite3_io_methods objects that
4979** implement various file locking strategies. It also contains definitions
4980** of "finder" functions. A finder-function is used to locate the appropriate
4981** sqlite3_io_methods object for a particular database file. The pAppData
4982** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4983** the correct finder-function for that VFS.
4984**
4985** Most finder functions return a pointer to a fixed sqlite3_io_methods
4986** object. The only interesting finder-function is autolockIoFinder, which
4987** looks at the filesystem type and tries to guess the best locking
4988** strategy from that.
4989**
peter.d.reid60ec9142014-09-06 16:39:46 +00004990** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004991**
4992** (1) The real finder-function named "FImpt()".
4993**
dane946c392009-08-22 11:39:46 +00004994** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004995**
4996**
4997** A pointer to the F pointer is used as the pAppData value for VFS
4998** objects. We have to do this instead of letting pAppData point
4999** directly at the finder-function since C90 rules prevent a void*
5000** from be cast into a function pointer.
5001**
drh6b9d6dd2008-12-03 19:34:47 +00005002**
drh7708e972008-11-29 00:56:52 +00005003** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005004**
drh7708e972008-11-29 00:56:52 +00005005** * A constant sqlite3_io_methods object call METHOD that has locking
5006** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5007**
5008** * An I/O method finder function called FINDER that returns a pointer
5009** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005010*/
drhe6d41732015-02-21 00:49:00 +00005011#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005012static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005013 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005014 CLOSE, /* xClose */ \
5015 unixRead, /* xRead */ \
5016 unixWrite, /* xWrite */ \
5017 unixTruncate, /* xTruncate */ \
5018 unixSync, /* xSync */ \
5019 unixFileSize, /* xFileSize */ \
5020 LOCK, /* xLock */ \
5021 UNLOCK, /* xUnlock */ \
5022 CKLOCK, /* xCheckReservedLock */ \
5023 unixFileControl, /* xFileControl */ \
5024 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005025 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005026 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005027 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005028 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005029 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005030 unixFetch, /* xFetch */ \
5031 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005032}; \
drh0c2694b2009-09-03 16:23:44 +00005033static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5034 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005035 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005036} \
drh0c2694b2009-09-03 16:23:44 +00005037static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005038 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005039
5040/*
5041** Here are all of the sqlite3_io_methods objects for each of the
5042** locking strategies. Functions that return pointers to these methods
5043** are also created.
5044*/
5045IOMETHODS(
5046 posixIoFinder, /* Finder function name */
5047 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005048 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005049 unixClose, /* xClose method */
5050 unixLock, /* xLock method */
5051 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005052 unixCheckReservedLock, /* xCheckReservedLock method */
5053 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005054)
drh7708e972008-11-29 00:56:52 +00005055IOMETHODS(
5056 nolockIoFinder, /* Finder function name */
5057 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005058 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005059 nolockClose, /* xClose method */
5060 nolockLock, /* xLock method */
5061 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005062 nolockCheckReservedLock, /* xCheckReservedLock method */
5063 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005064)
drh7708e972008-11-29 00:56:52 +00005065IOMETHODS(
5066 dotlockIoFinder, /* Finder function name */
5067 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005068 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005069 dotlockClose, /* xClose method */
5070 dotlockLock, /* xLock method */
5071 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005072 dotlockCheckReservedLock, /* xCheckReservedLock method */
5073 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005074)
drh7708e972008-11-29 00:56:52 +00005075
drhe89b2912015-03-03 20:42:01 +00005076#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005077IOMETHODS(
5078 flockIoFinder, /* Finder function name */
5079 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005080 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005081 flockClose, /* xClose method */
5082 flockLock, /* xLock method */
5083 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005084 flockCheckReservedLock, /* xCheckReservedLock method */
5085 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005086)
drh7708e972008-11-29 00:56:52 +00005087#endif
5088
drh6c7d5c52008-11-21 20:32:33 +00005089#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005090IOMETHODS(
5091 semIoFinder, /* Finder function name */
5092 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005093 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005094 semXClose, /* xClose method */
5095 semXLock, /* xLock method */
5096 semXUnlock, /* xUnlock method */
5097 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005098 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005099)
aswiftaebf4132008-11-21 00:10:35 +00005100#endif
drh7708e972008-11-29 00:56:52 +00005101
drhd2cb50b2009-01-09 21:41:17 +00005102#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005103IOMETHODS(
5104 afpIoFinder, /* Finder function name */
5105 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005106 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005107 afpClose, /* xClose method */
5108 afpLock, /* xLock method */
5109 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005110 afpCheckReservedLock, /* xCheckReservedLock method */
5111 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005112)
drh715ff302008-12-03 22:32:44 +00005113#endif
5114
5115/*
5116** The proxy locking method is a "super-method" in the sense that it
5117** opens secondary file descriptors for the conch and lock files and
5118** it uses proxy, dot-file, AFP, and flock() locking methods on those
5119** secondary files. For this reason, the division that implements
5120** proxy locking is located much further down in the file. But we need
5121** to go ahead and define the sqlite3_io_methods and finder function
5122** for proxy locking here. So we forward declare the I/O methods.
5123*/
drhd2cb50b2009-01-09 21:41:17 +00005124#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005125static int proxyClose(sqlite3_file*);
5126static int proxyLock(sqlite3_file*, int);
5127static int proxyUnlock(sqlite3_file*, int);
5128static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005129IOMETHODS(
5130 proxyIoFinder, /* Finder function name */
5131 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005132 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005133 proxyClose, /* xClose method */
5134 proxyLock, /* xLock method */
5135 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005136 proxyCheckReservedLock, /* xCheckReservedLock method */
5137 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005138)
aswiftaebf4132008-11-21 00:10:35 +00005139#endif
drh7708e972008-11-29 00:56:52 +00005140
drh7ed97b92010-01-20 13:07:21 +00005141/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5142#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5143IOMETHODS(
5144 nfsIoFinder, /* Finder function name */
5145 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005146 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005147 unixClose, /* xClose method */
5148 unixLock, /* xLock method */
5149 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005150 unixCheckReservedLock, /* xCheckReservedLock method */
5151 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005152)
5153#endif
drh7708e972008-11-29 00:56:52 +00005154
drhd2cb50b2009-01-09 21:41:17 +00005155#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005156/*
drh6b9d6dd2008-12-03 19:34:47 +00005157** This "finder" function attempts to determine the best locking strategy
5158** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005159** object that implements that strategy.
5160**
5161** This is for MacOSX only.
5162*/
drh1875f7a2008-12-08 18:19:17 +00005163static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005164 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005165 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005166){
5167 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005168 const char *zFilesystem; /* Filesystem type name */
5169 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005170 } aMap[] = {
5171 { "hfs", &posixIoMethods },
5172 { "ufs", &posixIoMethods },
5173 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005174 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005175 { "webdav", &nolockIoMethods },
5176 { 0, 0 }
5177 };
5178 int i;
5179 struct statfs fsInfo;
5180 struct flock lockInfo;
5181
5182 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005183 /* If filePath==NULL that means we are dealing with a transient file
5184 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005185 return &nolockIoMethods;
5186 }
5187 if( statfs(filePath, &fsInfo) != -1 ){
5188 if( fsInfo.f_flags & MNT_RDONLY ){
5189 return &nolockIoMethods;
5190 }
5191 for(i=0; aMap[i].zFilesystem; i++){
5192 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5193 return aMap[i].pMethods;
5194 }
5195 }
5196 }
5197
5198 /* Default case. Handles, amongst others, "nfs".
5199 ** Test byte-range lock using fcntl(). If the call succeeds,
5200 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005201 */
drh7708e972008-11-29 00:56:52 +00005202 lockInfo.l_len = 1;
5203 lockInfo.l_start = 0;
5204 lockInfo.l_whence = SEEK_SET;
5205 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005206 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005207 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5208 return &nfsIoMethods;
5209 } else {
5210 return &posixIoMethods;
5211 }
drh7708e972008-11-29 00:56:52 +00005212 }else{
5213 return &dotlockIoMethods;
5214 }
5215}
drh0c2694b2009-09-03 16:23:44 +00005216static const sqlite3_io_methods
5217 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005218
drhd2cb50b2009-01-09 21:41:17 +00005219#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005220
drhe89b2912015-03-03 20:42:01 +00005221#if OS_VXWORKS
5222/*
5223** This "finder" function for VxWorks checks to see if posix advisory
5224** locking works. If it does, then that is what is used. If it does not
5225** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005226*/
drhe89b2912015-03-03 20:42:01 +00005227static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005228 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005229 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005230){
5231 struct flock lockInfo;
5232
5233 if( !filePath ){
5234 /* If filePath==NULL that means we are dealing with a transient file
5235 ** that does not need to be locked. */
5236 return &nolockIoMethods;
5237 }
5238
5239 /* Test if fcntl() is supported and use POSIX style locks.
5240 ** Otherwise fall back to the named semaphore method.
5241 */
5242 lockInfo.l_len = 1;
5243 lockInfo.l_start = 0;
5244 lockInfo.l_whence = SEEK_SET;
5245 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005246 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005247 return &posixIoMethods;
5248 }else{
5249 return &semIoMethods;
5250 }
5251}
drh0c2694b2009-09-03 16:23:44 +00005252static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005253 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005254
drhe89b2912015-03-03 20:42:01 +00005255#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005256
drh7708e972008-11-29 00:56:52 +00005257/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005258** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005259*/
drh0c2694b2009-09-03 16:23:44 +00005260typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005261
aswiftaebf4132008-11-21 00:10:35 +00005262
drh734c9862008-11-28 15:37:20 +00005263/****************************************************************************
5264**************************** sqlite3_vfs methods ****************************
5265**
5266** This division contains the implementation of methods on the
5267** sqlite3_vfs object.
5268*/
5269
danielk1977a3d4c882007-03-23 10:08:38 +00005270/*
danielk1977e339d652008-06-28 11:23:00 +00005271** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005272*/
5273static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005274 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005275 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005276 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005277 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005278 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005279){
drh7708e972008-11-29 00:56:52 +00005280 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005281 unixFile *pNew = (unixFile *)pId;
5282 int rc = SQLITE_OK;
5283
drh8af6c222010-05-14 12:43:01 +00005284 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005285
dan00157392010-10-05 11:33:15 +00005286 /* Usually the path zFilename should not be a relative pathname. The
5287 ** exception is when opening the proxy "conch" file in builds that
5288 ** include the special Apple locking styles.
5289 */
dan00157392010-10-05 11:33:15 +00005290#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005291 assert( zFilename==0 || zFilename[0]=='/'
5292 || pVfs->pAppData==(void*)&autolockIoFinder );
5293#else
5294 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005295#endif
dan00157392010-10-05 11:33:15 +00005296
drhb07028f2011-10-14 21:49:18 +00005297 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005298 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005299
drh308c2a52010-05-14 11:30:18 +00005300 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005301 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005302 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005303 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005304 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005305#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005306 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005307#endif
drhc02a43a2012-01-10 23:18:38 +00005308 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5309 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005310 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005311 }
drh503a6862013-03-01 01:07:17 +00005312 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005313 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005314 }
drh339eb0b2008-03-07 15:34:11 +00005315
drh6c7d5c52008-11-21 20:32:33 +00005316#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005317 pNew->pId = vxworksFindFileId(zFilename);
5318 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005319 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005320 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005321 }
5322#endif
5323
drhc02a43a2012-01-10 23:18:38 +00005324 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005325 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005326 }else{
drh0c2694b2009-09-03 16:23:44 +00005327 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005328#if SQLITE_ENABLE_LOCKING_STYLE
5329 /* Cache zFilename in the locking context (AFP and dotlock override) for
5330 ** proxyLock activation is possible (remote proxy is based on db name)
5331 ** zFilename remains valid until file is closed, to support */
5332 pNew->lockingContext = (void*)zFilename;
5333#endif
drhda0e7682008-07-30 15:27:54 +00005334 }
danielk1977e339d652008-06-28 11:23:00 +00005335
drh7ed97b92010-01-20 13:07:21 +00005336 if( pLockingStyle == &posixIoMethods
5337#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5338 || pLockingStyle == &nfsIoMethods
5339#endif
5340 ){
drh7708e972008-11-29 00:56:52 +00005341 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005342 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005343 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005344 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005345 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005346 ** in two scenarios:
5347 **
5348 ** (a) A call to fstat() failed.
5349 ** (b) A malloc failed.
5350 **
5351 ** Scenario (b) may only occur if the process is holding no other
5352 ** file descriptors open on the same file. If there were other file
5353 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005354 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005355 ** handle h - as it is guaranteed that no posix locks will be released
5356 ** by doing so.
5357 **
5358 ** If scenario (a) caused the error then things are not so safe. The
5359 ** implicit assumption here is that if fstat() fails, things are in
5360 ** such bad shape that dropping a lock or two doesn't matter much.
5361 */
drh0e9365c2011-03-02 02:08:13 +00005362 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005363 h = -1;
5364 }
drh7708e972008-11-29 00:56:52 +00005365 unixLeaveMutex();
5366 }
danielk1977e339d652008-06-28 11:23:00 +00005367
drhd2cb50b2009-01-09 21:41:17 +00005368#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005369 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005370 /* AFP locking uses the file path so it needs to be included in
5371 ** the afpLockingContext.
5372 */
5373 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005374 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005375 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005376 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005377 }else{
5378 /* NB: zFilename exists and remains valid until the file is closed
5379 ** according to requirement F11141. So we do not need to make a
5380 ** copy of the filename. */
5381 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005382 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005383 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005384 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005385 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005386 if( rc!=SQLITE_OK ){
5387 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005388 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005389 h = -1;
5390 }
drh7708e972008-11-29 00:56:52 +00005391 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005392 }
drh7708e972008-11-29 00:56:52 +00005393 }
5394#endif
danielk1977e339d652008-06-28 11:23:00 +00005395
drh7708e972008-11-29 00:56:52 +00005396 else if( pLockingStyle == &dotlockIoMethods ){
5397 /* Dotfile locking uses the file path so it needs to be included in
5398 ** the dotlockLockingContext
5399 */
5400 char *zLockFile;
5401 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005402 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005403 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005404 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005405 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005406 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005407 }else{
5408 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005409 }
drh7708e972008-11-29 00:56:52 +00005410 pNew->lockingContext = zLockFile;
5411 }
danielk1977e339d652008-06-28 11:23:00 +00005412
drh6c7d5c52008-11-21 20:32:33 +00005413#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005414 else if( pLockingStyle == &semIoMethods ){
5415 /* Named semaphore locking uses the file path so it needs to be
5416 ** included in the semLockingContext
5417 */
5418 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005419 rc = findInodeInfo(pNew, &pNew->pInode);
5420 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5421 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005422 int n;
drh2238dcc2009-08-27 17:56:20 +00005423 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005424 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005425 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005426 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005427 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5428 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005429 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005430 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005431 }
chw97185482008-11-17 08:05:31 +00005432 }
drh7708e972008-11-29 00:56:52 +00005433 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005434 }
drh7708e972008-11-29 00:56:52 +00005435#endif
aswift5b1a2562008-08-22 00:22:35 +00005436
drh4bf66fd2015-02-19 02:43:02 +00005437 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005438#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005439 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005440 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005441 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005442 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005443 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005444 }
chw97185482008-11-17 08:05:31 +00005445#endif
danielk1977e339d652008-06-28 11:23:00 +00005446 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005447 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005448 }else{
drh7708e972008-11-29 00:56:52 +00005449 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005450 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005451 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005452 }
danielk1977e339d652008-06-28 11:23:00 +00005453 return rc;
drh054889e2005-11-30 03:20:31 +00005454}
drh9c06c952005-11-26 00:25:00 +00005455
danielk1977ad94b582007-08-20 06:44:22 +00005456/*
drh8b3cf822010-06-01 21:02:51 +00005457** Return the name of a directory in which to put temporary files.
5458** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005459*/
drh7234c6d2010-06-19 15:10:09 +00005460static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005461 static const char *azDirs[] = {
5462 0,
aswiftaebf4132008-11-21 00:10:35 +00005463 0,
danielk197717b90b52008-06-06 11:11:25 +00005464 "/var/tmp",
5465 "/usr/tmp",
5466 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005467 "."
danielk197717b90b52008-06-06 11:11:25 +00005468 };
drh2aab11f2016-04-29 20:30:56 +00005469 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005470 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005471 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005472
drhb7e50ad2015-11-28 21:49:53 +00005473 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5474 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005475 while(1){
5476 if( zDir!=0
5477 && osStat(zDir, &buf)==0
5478 && S_ISDIR(buf.st_mode)
5479 && osAccess(zDir, 03)==0
5480 ){
5481 return zDir;
5482 }
5483 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5484 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005485 }
drh7694e062016-04-21 23:37:24 +00005486 return 0;
drh8b3cf822010-06-01 21:02:51 +00005487}
5488
5489/*
5490** Create a temporary file name in zBuf. zBuf must be allocated
5491** by the calling process and must be big enough to hold at least
5492** pVfs->mxPathname bytes.
5493*/
5494static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005495 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005496 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005497
5498 /* It's odd to simulate an io-error here, but really this is just
5499 ** using the io-error infrastructure to test that SQLite handles this
5500 ** function failing.
5501 */
drh7694e062016-04-21 23:37:24 +00005502 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005503 SimulateIOError( return SQLITE_IOERR );
5504
drh7234c6d2010-06-19 15:10:09 +00005505 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005506 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005507 do{
drh970942e2015-11-25 23:13:14 +00005508 u64 r;
5509 sqlite3_randomness(sizeof(r), &r);
5510 assert( nBuf>2 );
5511 zBuf[nBuf-2] = 0;
5512 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5513 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005514 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005515 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005516 return SQLITE_OK;
5517}
5518
drhd2cb50b2009-01-09 21:41:17 +00005519#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005520/*
5521** Routine to transform a unixFile into a proxy-locking unixFile.
5522** Implementation in the proxy-lock division, but used by unixOpen()
5523** if SQLITE_PREFER_PROXY_LOCKING is defined.
5524*/
5525static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005526#endif
drhc66d5b62008-12-03 22:48:32 +00005527
dan08da86a2009-08-21 17:18:03 +00005528/*
5529** Search for an unused file descriptor that was opened on the database
5530** file (not a journal or master-journal file) identified by pathname
5531** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5532** argument to this function.
5533**
5534** Such a file descriptor may exist if a database connection was closed
5535** but the associated file descriptor could not be closed because some
5536** other file descriptor open on the same file is holding a file-lock.
5537** Refer to comments in the unixClose() function and the lengthy comment
5538** describing "Posix Advisory Locking" at the start of this file for
5539** further details. Also, ticket #4018.
5540**
5541** If a suitable file descriptor is found, then it is returned. If no
5542** such file descriptor is located, -1 is returned.
5543*/
dane946c392009-08-22 11:39:46 +00005544static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5545 UnixUnusedFd *pUnused = 0;
5546
5547 /* Do not search for an unused file descriptor on vxworks. Not because
5548 ** vxworks would not benefit from the change (it might, we're not sure),
5549 ** but because no way to test it is currently available. It is better
5550 ** not to risk breaking vxworks support for the sake of such an obscure
5551 ** feature. */
5552#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005553 struct stat sStat; /* Results of stat() call */
5554
5555 /* A stat() call may fail for various reasons. If this happens, it is
5556 ** almost certain that an open() call on the same path will also fail.
5557 ** For this reason, if an error occurs in the stat() call here, it is
5558 ** ignored and -1 is returned. The caller will try to open a new file
5559 ** descriptor on the same path, fail, and return an error to SQLite.
5560 **
5561 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005562 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005563 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005564 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005565
5566 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005567 pInode = inodeList;
5568 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005569 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005570 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005571 }
drh8af6c222010-05-14 12:43:01 +00005572 if( pInode ){
dane946c392009-08-22 11:39:46 +00005573 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005574 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005575 pUnused = *pp;
5576 if( pUnused ){
5577 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005578 }
5579 }
5580 unixLeaveMutex();
5581 }
dane946c392009-08-22 11:39:46 +00005582#endif /* if !OS_VXWORKS */
5583 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005584}
danielk197717b90b52008-06-06 11:11:25 +00005585
5586/*
dan1bf4ca72016-08-11 18:05:47 +00005587** Find the mode, uid and gid of file zFile.
5588*/
5589static int getFileMode(
5590 const char *zFile, /* File name */
5591 mode_t *pMode, /* OUT: Permissions of zFile */
5592 uid_t *pUid, /* OUT: uid of zFile. */
5593 gid_t *pGid /* OUT: gid of zFile. */
5594){
5595 struct stat sStat; /* Output of stat() on database file */
5596 int rc = SQLITE_OK;
5597 if( 0==osStat(zFile, &sStat) ){
5598 *pMode = sStat.st_mode & 0777;
5599 *pUid = sStat.st_uid;
5600 *pGid = sStat.st_gid;
5601 }else{
5602 rc = SQLITE_IOERR_FSTAT;
5603 }
5604 return rc;
5605}
5606
5607/*
danddb0ac42010-07-14 14:48:58 +00005608** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005609** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005610** and a value suitable for passing as the third argument to open(2) is
5611** written to *pMode. If an IO error occurs, an SQLite error code is
5612** returned and the value of *pMode is not modified.
5613**
peter.d.reid60ec9142014-09-06 16:39:46 +00005614** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005615** an indication to robust_open() to create the file using
5616** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5617** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005618** this function queries the file-system for the permissions on the
5619** corresponding database file and sets *pMode to this value. Whenever
5620** possible, WAL and journal files are created using the same permissions
5621** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005622**
5623** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5624** original filename is unavailable. But 8_3_NAMES is only used for
5625** FAT filesystems and permissions do not matter there, so just use
5626** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005627*/
5628static int findCreateFileMode(
5629 const char *zPath, /* Path of file (possibly) being created */
5630 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005631 mode_t *pMode, /* OUT: Permissions to open file with */
5632 uid_t *pUid, /* OUT: uid to set on the file */
5633 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005634){
5635 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005636 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005637 *pUid = 0;
5638 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005639 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005640 char zDb[MAX_PATHNAME+1]; /* Database file path */
5641 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005642
dana0c989d2010-11-05 18:07:37 +00005643 /* zPath is a path to a WAL or journal file. The following block derives
5644 ** the path to the associated database file from zPath. This block handles
5645 ** the following naming conventions:
5646 **
5647 ** "<path to db>-journal"
5648 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005649 ** "<path to db>-journalNN"
5650 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005651 **
drhd337c5b2011-10-20 18:23:35 +00005652 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005653 ** used by the test_multiplex.c module.
5654 */
5655 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005656 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005657#ifndef SQLITE_ENABLE_8_3_NAMES
5658 /* In the normal case (8+3 filenames disabled) the journal filename
5659 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005660 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005661 assert( sqlite3Isalnum(zPath[nDb]) );
5662#else
5663 /* If 8+3 names are possible, then the journal file might not contain
5664 ** a '-' character. So check for that case and return early. */
5665 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5666#endif
drhc47167a2011-10-05 15:26:13 +00005667 nDb--;
5668 }
danddb0ac42010-07-14 14:48:58 +00005669 memcpy(zDb, zPath, nDb);
5670 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005671
dan1bf4ca72016-08-11 18:05:47 +00005672 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005673 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5674 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005675 }else if( flags & SQLITE_OPEN_URI ){
5676 /* If this is a main database file and the file was opened using a URI
5677 ** filename, check for the "modeof" parameter. If present, interpret
5678 ** its value as a filename and try to copy the mode, uid and gid from
5679 ** that file. */
5680 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5681 if( z ){
5682 rc = getFileMode(z, pMode, pUid, pGid);
5683 }
danddb0ac42010-07-14 14:48:58 +00005684 }
5685 return rc;
5686}
5687
5688/*
danielk1977ad94b582007-08-20 06:44:22 +00005689** Open the file zPath.
5690**
danielk1977b4b47412007-08-17 15:53:36 +00005691** Previously, the SQLite OS layer used three functions in place of this
5692** one:
5693**
5694** sqlite3OsOpenReadWrite();
5695** sqlite3OsOpenReadOnly();
5696** sqlite3OsOpenExclusive();
5697**
5698** These calls correspond to the following combinations of flags:
5699**
5700** ReadWrite() -> (READWRITE | CREATE)
5701** ReadOnly() -> (READONLY)
5702** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5703**
5704** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5705** true, the file was configured to be automatically deleted when the
5706** file handle closed. To achieve the same effect using this new
5707** interface, add the DELETEONCLOSE flag to those specified above for
5708** OpenExclusive().
5709*/
5710static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005711 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5712 const char *zPath, /* Pathname of file to be opened */
5713 sqlite3_file *pFile, /* The file descriptor to be filled in */
5714 int flags, /* Input flags to control the opening */
5715 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005716){
dan08da86a2009-08-21 17:18:03 +00005717 unixFile *p = (unixFile *)pFile;
5718 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005719 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005720 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005721 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005722 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005723 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005724
5725 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5726 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5727 int isCreate = (flags & SQLITE_OPEN_CREATE);
5728 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5729 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005730#if SQLITE_ENABLE_LOCKING_STYLE
5731 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5732#endif
drh3d4435b2011-08-26 20:55:50 +00005733#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5734 struct statfs fsInfo;
5735#endif
danielk1977b4b47412007-08-17 15:53:36 +00005736
danielk1977fee2d252007-08-18 10:59:19 +00005737 /* If creating a master or main-file journal, this function will open
5738 ** a file-descriptor on the directory too. The first time unixSync()
5739 ** is called the directory file descriptor will be fsync()ed and close()d.
5740 */
drh0059eae2011-08-08 23:48:40 +00005741 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005742 eType==SQLITE_OPEN_MASTER_JOURNAL
5743 || eType==SQLITE_OPEN_MAIN_JOURNAL
5744 || eType==SQLITE_OPEN_WAL
5745 ));
danielk1977fee2d252007-08-18 10:59:19 +00005746
danielk197717b90b52008-06-06 11:11:25 +00005747 /* If argument zPath is a NULL pointer, this function is required to open
5748 ** a temporary file. Use this buffer to store the file name in.
5749 */
drhc02a43a2012-01-10 23:18:38 +00005750 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005751 const char *zName = zPath;
5752
danielk1977fee2d252007-08-18 10:59:19 +00005753 /* Check the following statements are true:
5754 **
5755 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5756 ** (b) if CREATE is set, then READWRITE must also be set, and
5757 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005758 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005759 */
danielk1977b4b47412007-08-17 15:53:36 +00005760 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005761 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005762 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005763 assert(isDelete==0 || isCreate);
5764
danddb0ac42010-07-14 14:48:58 +00005765 /* The main DB, main journal, WAL file and master journal are never
5766 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005767 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5768 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5769 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005770 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005771
danielk1977fee2d252007-08-18 10:59:19 +00005772 /* Assert that the upper layer has set one of the "file-type" flags. */
5773 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5774 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5775 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005776 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005777 );
5778
drhb00d8622014-01-01 15:18:36 +00005779 /* Detect a pid change and reset the PRNG. There is a race condition
5780 ** here such that two or more threads all trying to open databases at
5781 ** the same instant might all reset the PRNG. But multiple resets
5782 ** are harmless.
5783 */
drh5ac93652015-03-21 20:59:43 +00005784 if( randomnessPid!=osGetpid(0) ){
5785 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005786 sqlite3_randomness(0,0);
5787 }
5788
dan08da86a2009-08-21 17:18:03 +00005789 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005790
dan08da86a2009-08-21 17:18:03 +00005791 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005792 UnixUnusedFd *pUnused;
5793 pUnused = findReusableFd(zName, flags);
5794 if( pUnused ){
5795 fd = pUnused->fd;
5796 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005797 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005798 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005799 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005800 }
5801 }
5802 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005803
5804 /* Database filenames are double-zero terminated if they are not
5805 ** URIs with parameters. Hence, they can always be passed into
5806 ** sqlite3_uri_parameter(). */
5807 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5808
dan08da86a2009-08-21 17:18:03 +00005809 }else if( !zName ){
5810 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005811 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005812 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005813 if( rc!=SQLITE_OK ){
5814 return rc;
5815 }
5816 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005817
5818 /* Generated temporary filenames are always double-zero terminated
5819 ** for use by sqlite3_uri_parameter(). */
5820 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005821 }
5822
dan08da86a2009-08-21 17:18:03 +00005823 /* Determine the value of the flags parameter passed to POSIX function
5824 ** open(). These must be calculated even if open() is not called, as
5825 ** they may be stored as part of the file handle and used by the
5826 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005827 if( isReadonly ) openFlags |= O_RDONLY;
5828 if( isReadWrite ) openFlags |= O_RDWR;
5829 if( isCreate ) openFlags |= O_CREAT;
5830 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5831 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005832
danielk1977b4b47412007-08-17 15:53:36 +00005833 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005834 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005835 uid_t uid; /* Userid for the file */
5836 gid_t gid; /* Groupid for the file */
5837 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005838 if( rc!=SQLITE_OK ){
5839 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005840 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005841 return rc;
5842 }
drhad4f1e52011-03-04 15:43:57 +00005843 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005844 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005845 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5846 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005847 /* Failed to open the file for read/write access. Try read-only. */
5848 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005849 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005850 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005851 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005852 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005853 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005854 }
5855 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005856 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005857 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005858 }
drhac7c3ac2012-02-11 19:23:48 +00005859
5860 /* If this process is running as root and if creating a new rollback
5861 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005862 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005863 */
5864 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005865 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005866 }
danielk1977b4b47412007-08-17 15:53:36 +00005867 }
dan08da86a2009-08-21 17:18:03 +00005868 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005869 if( pOutFlags ){
5870 *pOutFlags = flags;
5871 }
5872
dane946c392009-08-22 11:39:46 +00005873 if( p->pUnused ){
5874 p->pUnused->fd = fd;
5875 p->pUnused->flags = flags;
5876 }
5877
danielk1977b4b47412007-08-17 15:53:36 +00005878 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005879#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005880 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005881#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5882 zPath = sqlite3_mprintf("%s", zName);
5883 if( zPath==0 ){
5884 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00005885 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00005886 }
chw97185482008-11-17 08:05:31 +00005887#else
drh036ac7f2011-08-08 23:18:05 +00005888 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005889#endif
danielk1977b4b47412007-08-17 15:53:36 +00005890 }
drh41022642008-11-21 00:24:42 +00005891#if SQLITE_ENABLE_LOCKING_STYLE
5892 else{
dan08da86a2009-08-21 17:18:03 +00005893 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005894 }
5895#endif
drh7ed97b92010-01-20 13:07:21 +00005896
5897#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005898 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005899 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005900 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005901 return SQLITE_IOERR_ACCESS;
5902 }
5903 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5904 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5905 }
drh4bf66fd2015-02-19 02:43:02 +00005906 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5907 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5908 }
drh7ed97b92010-01-20 13:07:21 +00005909#endif
drhc02a43a2012-01-10 23:18:38 +00005910
5911 /* Set up appropriate ctrlFlags */
5912 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5913 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00005914 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00005915 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5916 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5917 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5918
drh7ed97b92010-01-20 13:07:21 +00005919#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005920#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005921 isAutoProxy = 1;
5922#endif
5923 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005924 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5925 int useProxy = 0;
5926
dan08da86a2009-08-21 17:18:03 +00005927 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5928 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005929 if( envforce!=NULL ){
5930 useProxy = atoi(envforce)>0;
5931 }else{
aswiftaebf4132008-11-21 00:10:35 +00005932 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5933 }
5934 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005935 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005936 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005937 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005938 if( rc!=SQLITE_OK ){
5939 /* Use unixClose to clean up the resources added in fillInUnixFile
5940 ** and clear all the structure's references. Specifically,
5941 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5942 */
5943 unixClose(pFile);
5944 return rc;
5945 }
aswiftaebf4132008-11-21 00:10:35 +00005946 }
dane946c392009-08-22 11:39:46 +00005947 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005948 }
5949 }
5950#endif
5951
drhc02a43a2012-01-10 23:18:38 +00005952 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5953
dane946c392009-08-22 11:39:46 +00005954open_finished:
5955 if( rc!=SQLITE_OK ){
5956 sqlite3_free(p->pUnused);
5957 }
5958 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005959}
5960
dane946c392009-08-22 11:39:46 +00005961
danielk1977b4b47412007-08-17 15:53:36 +00005962/*
danielk1977fee2d252007-08-18 10:59:19 +00005963** Delete the file at zPath. If the dirSync argument is true, fsync()
5964** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005965*/
drh6b9d6dd2008-12-03 19:34:47 +00005966static int unixDelete(
5967 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5968 const char *zPath, /* Name of file to be deleted */
5969 int dirSync /* If true, fsync() directory after deleting file */
5970){
danielk1977fee2d252007-08-18 10:59:19 +00005971 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005972 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005973 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005974 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005975 if( errno==ENOENT
5976#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005977 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005978#endif
5979 ){
dan9fc5b4a2012-11-09 20:17:26 +00005980 rc = SQLITE_IOERR_DELETE_NOENT;
5981 }else{
drhb4308162012-11-09 21:40:02 +00005982 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005983 }
drhb4308162012-11-09 21:40:02 +00005984 return rc;
drh5d4feff2010-07-14 01:45:22 +00005985 }
danielk1977d39fa702008-10-16 13:27:40 +00005986#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005987 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005988 int fd;
drh90315a22011-08-10 01:52:12 +00005989 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005990 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00005991 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00005992 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005993 }
drh0e9365c2011-03-02 02:08:13 +00005994 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005995 }else{
5996 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005997 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005998 }
5999 }
danielk1977d138dd82008-10-15 16:02:48 +00006000#endif
danielk1977fee2d252007-08-18 10:59:19 +00006001 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006002}
6003
danielk197790949c22007-08-17 16:50:38 +00006004/*
mistachkin48864df2013-03-21 21:20:32 +00006005** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006006** test performed depends on the value of flags:
6007**
6008** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6009** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6010** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6011**
6012** Otherwise return 0.
6013*/
danielk1977861f7452008-06-05 11:39:11 +00006014static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006015 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6016 const char *zPath, /* Path of the file to examine */
6017 int flags, /* What do we want to learn about the zPath file? */
6018 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006019){
danielk1977397d65f2008-11-19 11:35:39 +00006020 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006021 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006022 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006023
drhd260b5b2015-11-25 18:03:33 +00006024 /* The spec says there are three possible values for flags. But only
6025 ** two of them are actually used */
6026 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6027
6028 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006029 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006030 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6031 }else{
6032 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006033 }
danielk1977861f7452008-06-05 11:39:11 +00006034 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006035}
6036
danielk1977b4b47412007-08-17 15:53:36 +00006037/*
danielk1977b4b47412007-08-17 15:53:36 +00006038**
danielk1977b4b47412007-08-17 15:53:36 +00006039*/
dane88ec182016-01-25 17:04:48 +00006040static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006041 const char *zPath, /* Input path */
6042 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006043 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006044){
dancaf6b152016-01-25 18:05:49 +00006045 int nPath = sqlite3Strlen30(zPath);
6046 int iOff = 0;
6047 if( zPath[0]!='/' ){
6048 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006049 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006050 }
dancaf6b152016-01-25 18:05:49 +00006051 iOff = sqlite3Strlen30(zOut);
6052 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006053 }
dan23496702016-01-26 13:56:42 +00006054 if( (iOff+nPath+1)>nOut ){
6055 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6056 ** even if it returns an error. */
6057 zOut[iOff] = '\0';
6058 return SQLITE_CANTOPEN_BKPT;
6059 }
dancaf6b152016-01-25 18:05:49 +00006060 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006061 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006062}
6063
dane88ec182016-01-25 17:04:48 +00006064/*
6065** Turn a relative pathname into a full pathname. The relative path
6066** is stored as a nul-terminated string in the buffer pointed to by
6067** zPath.
6068**
6069** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6070** (in this case, MAX_PATHNAME bytes). The full-path is written to
6071** this buffer before returning.
6072*/
6073static int unixFullPathname(
6074 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6075 const char *zPath, /* Possibly relative input path */
6076 int nOut, /* Size of output buffer in bytes */
6077 char *zOut /* Output buffer */
6078){
danaf1b36b2016-01-25 18:43:05 +00006079#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006080 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006081#else
6082 int rc = SQLITE_OK;
6083 int nByte;
dancaf6b152016-01-25 18:05:49 +00006084 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006085 const char *zIn = zPath; /* Input path for each iteration of loop */
6086 char *zDel = 0;
6087
6088 assert( pVfs->mxPathname==MAX_PATHNAME );
6089 UNUSED_PARAMETER(pVfs);
6090
6091 /* It's odd to simulate an io-error here, but really this is just
6092 ** using the io-error infrastructure to test that SQLite handles this
6093 ** function failing. This function could fail if, for example, the
6094 ** current working directory has been unlinked.
6095 */
6096 SimulateIOError( return SQLITE_ERROR );
6097
6098 do {
6099
dancaf6b152016-01-25 18:05:49 +00006100 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6101 ** link, or false otherwise. */
6102 int bLink = 0;
6103 struct stat buf;
6104 if( osLstat(zIn, &buf)!=0 ){
6105 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006106 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006107 }
dane88ec182016-01-25 17:04:48 +00006108 }else{
dancaf6b152016-01-25 18:05:49 +00006109 bLink = S_ISLNK(buf.st_mode);
6110 }
6111
6112 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006113 if( zDel==0 ){
6114 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006115 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006116 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6117 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006118 }
dancaf6b152016-01-25 18:05:49 +00006119
6120 if( rc==SQLITE_OK ){
6121 nByte = osReadlink(zIn, zDel, nOut-1);
6122 if( nByte<0 ){
6123 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006124 }else{
6125 if( zDel[0]!='/' ){
6126 int n;
6127 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6128 if( nByte+n+1>nOut ){
6129 rc = SQLITE_CANTOPEN_BKPT;
6130 }else{
6131 memmove(&zDel[n], zDel, nByte+1);
6132 memcpy(zDel, zIn, n);
6133 nByte += n;
6134 }
dancaf6b152016-01-25 18:05:49 +00006135 }
6136 zDel[nByte] = '\0';
6137 }
6138 }
6139
6140 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006141 }
6142
dan23496702016-01-26 13:56:42 +00006143 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6144 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006145 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006146 }
dancaf6b152016-01-25 18:05:49 +00006147 if( bLink==0 ) break;
6148 zIn = zOut;
6149 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006150
6151 sqlite3_free(zDel);
6152 return rc;
danaf1b36b2016-01-25 18:43:05 +00006153#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006154}
6155
drh0ccebe72005-06-07 22:22:50 +00006156
drh761df872006-12-21 01:29:22 +00006157#ifndef SQLITE_OMIT_LOAD_EXTENSION
6158/*
6159** Interfaces for opening a shared library, finding entry points
6160** within the shared library, and closing the shared library.
6161*/
6162#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006163static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6164 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006165 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6166}
danielk197795c8a542007-09-01 06:51:27 +00006167
6168/*
6169** SQLite calls this function immediately after a call to unixDlSym() or
6170** unixDlOpen() fails (returns a null pointer). If a more detailed error
6171** message is available, it is written to zBufOut. If no error message
6172** is available, zBufOut is left unmodified and SQLite uses a default
6173** error message.
6174*/
danielk1977397d65f2008-11-19 11:35:39 +00006175static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006176 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006177 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006178 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006179 zErr = dlerror();
6180 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006181 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006182 }
drh6c7d5c52008-11-21 20:32:33 +00006183 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006184}
drh1875f7a2008-12-08 18:19:17 +00006185static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6186 /*
6187 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6188 ** cast into a pointer to a function. And yet the library dlsym() routine
6189 ** returns a void* which is really a pointer to a function. So how do we
6190 ** use dlsym() with -pedantic-errors?
6191 **
6192 ** Variable x below is defined to be a pointer to a function taking
6193 ** parameters void* and const char* and returning a pointer to a function.
6194 ** We initialize x by assigning it a pointer to the dlsym() function.
6195 ** (That assignment requires a cast.) Then we call the function that
6196 ** x points to.
6197 **
6198 ** This work-around is unlikely to work correctly on any system where
6199 ** you really cannot cast a function pointer into void*. But then, on the
6200 ** other hand, dlsym() will not work on such a system either, so we have
6201 ** not really lost anything.
6202 */
6203 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006204 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006205 x = (void(*(*)(void*,const char*))(void))dlsym;
6206 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006207}
danielk1977397d65f2008-11-19 11:35:39 +00006208static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6209 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006210 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006211}
danielk1977b4b47412007-08-17 15:53:36 +00006212#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6213 #define unixDlOpen 0
6214 #define unixDlError 0
6215 #define unixDlSym 0
6216 #define unixDlClose 0
6217#endif
6218
6219/*
danielk197790949c22007-08-17 16:50:38 +00006220** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006221*/
danielk1977397d65f2008-11-19 11:35:39 +00006222static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6223 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006224 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006225
drhbbd42a62004-05-22 17:41:58 +00006226 /* We have to initialize zBuf to prevent valgrind from reporting
6227 ** errors. The reports issued by valgrind are incorrect - we would
6228 ** prefer that the randomness be increased by making use of the
6229 ** uninitialized space in zBuf - but valgrind errors tend to worry
6230 ** some users. Rather than argue, it seems easier just to initialize
6231 ** the whole array and silence valgrind, even if that means less randomness
6232 ** in the random seed.
6233 **
6234 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006235 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006236 ** tests repeatable.
6237 */
danielk1977b4b47412007-08-17 15:53:36 +00006238 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006239 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006240#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006241 {
drhb00d8622014-01-01 15:18:36 +00006242 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006243 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006244 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006245 time_t t;
6246 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006247 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006248 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6249 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6250 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006251 }else{
drhc18b4042012-02-10 03:10:27 +00006252 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006253 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006254 }
drhbbd42a62004-05-22 17:41:58 +00006255 }
6256#endif
drh72cbd072008-10-14 17:58:38 +00006257 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006258}
6259
danielk1977b4b47412007-08-17 15:53:36 +00006260
drhbbd42a62004-05-22 17:41:58 +00006261/*
6262** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006263** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006264** The return value is the number of microseconds of sleep actually
6265** requested from the underlying operating system, a number which
6266** might be greater than or equal to the argument, but not less
6267** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006268*/
danielk1977397d65f2008-11-19 11:35:39 +00006269static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006270#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006271 struct timespec sp;
6272
6273 sp.tv_sec = microseconds / 1000000;
6274 sp.tv_nsec = (microseconds % 1000000) * 1000;
6275 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006276 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006277 return microseconds;
6278#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006279 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006280 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006281 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006282#else
danielk1977b4b47412007-08-17 15:53:36 +00006283 int seconds = (microseconds+999999)/1000000;
6284 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006285 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006286 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006287#endif
drh88f474a2006-01-02 20:00:12 +00006288}
6289
6290/*
drh6b9d6dd2008-12-03 19:34:47 +00006291** The following variable, if set to a non-zero value, is interpreted as
6292** the number of seconds since 1970 and is used to set the result of
6293** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006294*/
6295#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006296int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006297#endif
6298
6299/*
drhb7e8ea22010-05-03 14:32:30 +00006300** Find the current time (in Universal Coordinated Time). Write into *piNow
6301** the current time and date as a Julian Day number times 86_400_000. In
6302** other words, write into *piNow the number of milliseconds since the Julian
6303** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6304** proleptic Gregorian calendar.
6305**
drh31702252011-10-12 23:13:43 +00006306** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6307** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006308*/
6309static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6310 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006311 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006312#if defined(NO_GETTOD)
6313 time_t t;
6314 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006315 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006316#elif OS_VXWORKS
6317 struct timespec sNow;
6318 clock_gettime(CLOCK_REALTIME, &sNow);
6319 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6320#else
6321 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006322 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6323 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006324#endif
6325
6326#ifdef SQLITE_TEST
6327 if( sqlite3_current_time ){
6328 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6329 }
6330#endif
6331 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006332 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006333}
6334
drhc3dfa5e2016-01-22 19:44:03 +00006335#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006336/*
drhbbd42a62004-05-22 17:41:58 +00006337** Find the current time (in Universal Coordinated Time). Write the
6338** current time and date as a Julian Day number into *prNow and
6339** return 0. Return 1 if the time and date cannot be found.
6340*/
danielk1977397d65f2008-11-19 11:35:39 +00006341static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006342 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006343 int rc;
drhff828942010-06-26 21:34:06 +00006344 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006345 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006346 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006347 return rc;
drhbbd42a62004-05-22 17:41:58 +00006348}
drh5337dac2015-11-25 15:15:03 +00006349#else
6350# define unixCurrentTime 0
6351#endif
danielk1977b4b47412007-08-17 15:53:36 +00006352
drh6b9d6dd2008-12-03 19:34:47 +00006353/*
drh1b9f2142016-03-17 16:01:23 +00006354** The xGetLastError() method is designed to return a better
6355** low-level error message when operating-system problems come up
6356** during SQLite operation. Only the integer return code is currently
6357** used.
drh6b9d6dd2008-12-03 19:34:47 +00006358*/
danielk1977397d65f2008-11-19 11:35:39 +00006359static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6360 UNUSED_PARAMETER(NotUsed);
6361 UNUSED_PARAMETER(NotUsed2);
6362 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006363 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006364}
6365
drhf2424c52010-04-26 00:04:55 +00006366
6367/*
drh734c9862008-11-28 15:37:20 +00006368************************ End of sqlite3_vfs methods ***************************
6369******************************************************************************/
6370
drh715ff302008-12-03 22:32:44 +00006371/******************************************************************************
6372************************** Begin Proxy Locking ********************************
6373**
6374** Proxy locking is a "uber-locking-method" in this sense: It uses the
6375** other locking methods on secondary lock files. Proxy locking is a
6376** meta-layer over top of the primitive locking implemented above. For
6377** this reason, the division that implements of proxy locking is deferred
6378** until late in the file (here) after all of the other I/O methods have
6379** been defined - so that the primitive locking methods are available
6380** as services to help with the implementation of proxy locking.
6381**
6382****
6383**
6384** The default locking schemes in SQLite use byte-range locks on the
6385** database file to coordinate safe, concurrent access by multiple readers
6386** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6387** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6388** as POSIX read & write locks over fixed set of locations (via fsctl),
6389** on AFP and SMB only exclusive byte-range locks are available via fsctl
6390** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6391** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6392** address in the shared range is taken for a SHARED lock, the entire
6393** shared range is taken for an EXCLUSIVE lock):
6394**
drhf2f105d2012-08-20 15:53:54 +00006395** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006396** RESERVED_BYTE 0x40000001
6397** SHARED_RANGE 0x40000002 -> 0x40000200
6398**
6399** This works well on the local file system, but shows a nearly 100x
6400** slowdown in read performance on AFP because the AFP client disables
6401** the read cache when byte-range locks are present. Enabling the read
6402** cache exposes a cache coherency problem that is present on all OS X
6403** supported network file systems. NFS and AFP both observe the
6404** close-to-open semantics for ensuring cache coherency
6405** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6406** address the requirements for concurrent database access by multiple
6407** readers and writers
6408** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6409**
6410** To address the performance and cache coherency issues, proxy file locking
6411** changes the way database access is controlled by limiting access to a
6412** single host at a time and moving file locks off of the database file
6413** and onto a proxy file on the local file system.
6414**
6415**
6416** Using proxy locks
6417** -----------------
6418**
6419** C APIs
6420**
drh4bf66fd2015-02-19 02:43:02 +00006421** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006422** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006423** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6424** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006425**
6426**
6427** SQL pragmas
6428**
6429** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6430** PRAGMA [database.]lock_proxy_file
6431**
6432** Specifying ":auto:" means that if there is a conch file with a matching
6433** host ID in it, the proxy path in the conch file will be used, otherwise
6434** a proxy path based on the user's temp dir
6435** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6436** actual proxy file name is generated from the name and path of the
6437** database file. For example:
6438**
6439** For database path "/Users/me/foo.db"
6440** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6441**
6442** Once a lock proxy is configured for a database connection, it can not
6443** be removed, however it may be switched to a different proxy path via
6444** the above APIs (assuming the conch file is not being held by another
6445** connection or process).
6446**
6447**
6448** How proxy locking works
6449** -----------------------
6450**
6451** Proxy file locking relies primarily on two new supporting files:
6452**
6453** * conch file to limit access to the database file to a single host
6454** at a time
6455**
6456** * proxy file to act as a proxy for the advisory locks normally
6457** taken on the database
6458**
6459** The conch file - to use a proxy file, sqlite must first "hold the conch"
6460** by taking an sqlite-style shared lock on the conch file, reading the
6461** contents and comparing the host's unique host ID (see below) and lock
6462** proxy path against the values stored in the conch. The conch file is
6463** stored in the same directory as the database file and the file name
6464** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006465** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006466** host ID and/or proxy path, then the lock is escalated to an exclusive
6467** lock and the conch file contents is updated with the host ID and proxy
6468** path and the lock is downgraded to a shared lock again. If the conch
6469** is held by another process (with a shared lock), the exclusive lock
6470** will fail and SQLITE_BUSY is returned.
6471**
6472** The proxy file - a single-byte file used for all advisory file locks
6473** normally taken on the database file. This allows for safe sharing
6474** of the database file for multiple readers and writers on the same
6475** host (the conch ensures that they all use the same local lock file).
6476**
drh715ff302008-12-03 22:32:44 +00006477** Requesting the lock proxy does not immediately take the conch, it is
6478** only taken when the first request to lock database file is made.
6479** This matches the semantics of the traditional locking behavior, where
6480** opening a connection to a database file does not take a lock on it.
6481** The shared lock and an open file descriptor are maintained until
6482** the connection to the database is closed.
6483**
6484** The proxy file and the lock file are never deleted so they only need
6485** to be created the first time they are used.
6486**
6487** Configuration options
6488** ---------------------
6489**
6490** SQLITE_PREFER_PROXY_LOCKING
6491**
6492** Database files accessed on non-local file systems are
6493** automatically configured for proxy locking, lock files are
6494** named automatically using the same logic as
6495** PRAGMA lock_proxy_file=":auto:"
6496**
6497** SQLITE_PROXY_DEBUG
6498**
6499** Enables the logging of error messages during host id file
6500** retrieval and creation
6501**
drh715ff302008-12-03 22:32:44 +00006502** LOCKPROXYDIR
6503**
6504** Overrides the default directory used for lock proxy files that
6505** are named automatically via the ":auto:" setting
6506**
6507** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6508**
6509** Permissions to use when creating a directory for storing the
6510** lock proxy files, only used when LOCKPROXYDIR is not set.
6511**
6512**
6513** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6514** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6515** force proxy locking to be used for every database file opened, and 0
6516** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006517** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006518** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6519*/
6520
6521/*
6522** Proxy locking is only available on MacOSX
6523*/
drhd2cb50b2009-01-09 21:41:17 +00006524#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006525
drh715ff302008-12-03 22:32:44 +00006526/*
6527** The proxyLockingContext has the path and file structures for the remote
6528** and local proxy files in it
6529*/
6530typedef struct proxyLockingContext proxyLockingContext;
6531struct proxyLockingContext {
6532 unixFile *conchFile; /* Open conch file */
6533 char *conchFilePath; /* Name of the conch file */
6534 unixFile *lockProxy; /* Open proxy lock file */
6535 char *lockProxyPath; /* Name of the proxy lock file */
6536 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006537 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006538 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006539 void *oldLockingContext; /* Original lockingcontext to restore on close */
6540 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6541};
6542
drh7ed97b92010-01-20 13:07:21 +00006543/*
6544** The proxy lock file path for the database at dbPath is written into lPath,
6545** which must point to valid, writable memory large enough for a maxLen length
6546** file path.
drh715ff302008-12-03 22:32:44 +00006547*/
drh715ff302008-12-03 22:32:44 +00006548static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6549 int len;
6550 int dbLen;
6551 int i;
6552
6553#ifdef LOCKPROXYDIR
6554 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6555#else
6556# ifdef _CS_DARWIN_USER_TEMP_DIR
6557 {
drh7ed97b92010-01-20 13:07:21 +00006558 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006559 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006560 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006561 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006562 }
drh7ed97b92010-01-20 13:07:21 +00006563 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006564 }
6565# else
6566 len = strlcpy(lPath, "/tmp/", maxLen);
6567# endif
6568#endif
6569
6570 if( lPath[len-1]!='/' ){
6571 len = strlcat(lPath, "/", maxLen);
6572 }
6573
6574 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006575 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006576 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006577 char c = dbPath[i];
6578 lPath[i+len] = (c=='/')?'_':c;
6579 }
6580 lPath[i+len]='\0';
6581 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006582 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006583 return SQLITE_OK;
6584}
6585
drh7ed97b92010-01-20 13:07:21 +00006586/*
6587 ** Creates the lock file and any missing directories in lockPath
6588 */
6589static int proxyCreateLockPath(const char *lockPath){
6590 int i, len;
6591 char buf[MAXPATHLEN];
6592 int start = 0;
6593
6594 assert(lockPath!=NULL);
6595 /* try to create all the intermediate directories */
6596 len = (int)strlen(lockPath);
6597 buf[0] = lockPath[0];
6598 for( i=1; i<len; i++ ){
6599 if( lockPath[i] == '/' && (i - start > 0) ){
6600 /* only mkdir if leaf dir != "." or "/" or ".." */
6601 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6602 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6603 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006604 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006605 int err=errno;
6606 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006607 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006608 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006609 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006610 return err;
6611 }
6612 }
6613 }
6614 start=i+1;
6615 }
6616 buf[i] = lockPath[i];
6617 }
drh62aaa6c2015-11-21 17:27:42 +00006618 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006619 return 0;
6620}
6621
drh715ff302008-12-03 22:32:44 +00006622/*
6623** Create a new VFS file descriptor (stored in memory obtained from
6624** sqlite3_malloc) and open the file named "path" in the file descriptor.
6625**
6626** The caller is responsible not only for closing the file descriptor
6627** but also for freeing the memory associated with the file descriptor.
6628*/
drh7ed97b92010-01-20 13:07:21 +00006629static int proxyCreateUnixFile(
6630 const char *path, /* path for the new unixFile */
6631 unixFile **ppFile, /* unixFile created and returned by ref */
6632 int islockfile /* if non zero missing dirs will be created */
6633) {
6634 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006635 unixFile *pNew;
6636 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006637 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006638 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006639 int terrno = 0;
6640 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006641
drh7ed97b92010-01-20 13:07:21 +00006642 /* 1. first try to open/create the file
6643 ** 2. if that fails, and this is a lock file (not-conch), try creating
6644 ** the parent directories and then try again.
6645 ** 3. if that fails, try to open the file read-only
6646 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6647 */
6648 pUnused = findReusableFd(path, openFlags);
6649 if( pUnused ){
6650 fd = pUnused->fd;
6651 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006652 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006653 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006654 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006655 }
6656 }
6657 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006658 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006659 terrno = errno;
6660 if( fd<0 && errno==ENOENT && islockfile ){
6661 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006662 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006663 }
6664 }
6665 }
6666 if( fd<0 ){
6667 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006668 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006669 terrno = errno;
6670 }
6671 if( fd<0 ){
6672 if( islockfile ){
6673 return SQLITE_BUSY;
6674 }
6675 switch (terrno) {
6676 case EACCES:
6677 return SQLITE_PERM;
6678 case EIO:
6679 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6680 default:
drh9978c972010-02-23 17:36:32 +00006681 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006682 }
6683 }
6684
drhf3cdcdc2015-04-29 16:50:28 +00006685 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006686 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006687 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006688 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006689 }
6690 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006691 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006692 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006693 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006694 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006695 pUnused->fd = fd;
6696 pUnused->flags = openFlags;
6697 pNew->pUnused = pUnused;
6698
drhc02a43a2012-01-10 23:18:38 +00006699 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006700 if( rc==SQLITE_OK ){
6701 *ppFile = pNew;
6702 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006703 }
drh7ed97b92010-01-20 13:07:21 +00006704end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006705 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006706 sqlite3_free(pNew);
6707 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006708 return rc;
6709}
6710
drh7ed97b92010-01-20 13:07:21 +00006711#ifdef SQLITE_TEST
6712/* simulate multiple hosts by creating unique hostid file paths */
6713int sqlite3_hostid_num = 0;
6714#endif
6715
6716#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6717
drh6bca6512015-04-13 23:05:28 +00006718#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006719/* Not always defined in the headers as it ought to be */
6720extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006721#endif
drh0ab216a2010-07-02 17:10:40 +00006722
drh7ed97b92010-01-20 13:07:21 +00006723/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6724** bytes of writable memory.
6725*/
6726static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006727 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6728 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006729#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006730 {
drh4bf66fd2015-02-19 02:43:02 +00006731 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006732 if( gethostuuid(pHostID, &timeout) ){
6733 int err = errno;
6734 if( pError ){
6735 *pError = err;
6736 }
6737 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006738 }
drh7ed97b92010-01-20 13:07:21 +00006739 }
drh3d4435b2011-08-26 20:55:50 +00006740#else
6741 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006742#endif
drh7ed97b92010-01-20 13:07:21 +00006743#ifdef SQLITE_TEST
6744 /* simulate multiple hosts by creating unique hostid file paths */
6745 if( sqlite3_hostid_num != 0){
6746 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6747 }
6748#endif
6749
6750 return SQLITE_OK;
6751}
6752
6753/* The conch file contains the header, host id and lock file path
6754 */
6755#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6756#define PROXY_HEADERLEN 1 /* conch file header length */
6757#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6758#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6759
6760/*
6761** Takes an open conch file, copies the contents to a new path and then moves
6762** it back. The newly created file's file descriptor is assigned to the
6763** conch file structure and finally the original conch file descriptor is
6764** closed. Returns zero if successful.
6765*/
6766static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6767 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6768 unixFile *conchFile = pCtx->conchFile;
6769 char tPath[MAXPATHLEN];
6770 char buf[PROXY_MAXCONCHLEN];
6771 char *cPath = pCtx->conchFilePath;
6772 size_t readLen = 0;
6773 size_t pathLen = 0;
6774 char errmsg[64] = "";
6775 int fd = -1;
6776 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006777 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006778
6779 /* create a new path by replace the trailing '-conch' with '-break' */
6780 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6781 if( pathLen>MAXPATHLEN || pathLen<6 ||
6782 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006783 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006784 goto end_breaklock;
6785 }
6786 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006787 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006788 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006789 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006790 goto end_breaklock;
6791 }
6792 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006793 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006794 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006795 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006796 goto end_breaklock;
6797 }
drhe562be52011-03-02 18:01:10 +00006798 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006799 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006800 goto end_breaklock;
6801 }
6802 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006803 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006804 goto end_breaklock;
6805 }
6806 rc = 0;
6807 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006808 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006809 conchFile->h = fd;
6810 conchFile->openFlags = O_RDWR | O_CREAT;
6811
6812end_breaklock:
6813 if( rc ){
6814 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006815 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006816 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006817 }
6818 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6819 }
6820 return rc;
6821}
6822
6823/* Take the requested lock on the conch file and break a stale lock if the
6824** host id matches.
6825*/
6826static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6827 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6828 unixFile *conchFile = pCtx->conchFile;
6829 int rc = SQLITE_OK;
6830 int nTries = 0;
6831 struct timespec conchModTime;
6832
drh3d4435b2011-08-26 20:55:50 +00006833 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006834 do {
6835 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6836 nTries ++;
6837 if( rc==SQLITE_BUSY ){
6838 /* If the lock failed (busy):
6839 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6840 * 2nd try: fail if the mod time changed or host id is different, wait
6841 * 10 sec and try again
6842 * 3rd try: break the lock unless the mod time has changed.
6843 */
6844 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006845 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006846 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006847 return SQLITE_IOERR_LOCK;
6848 }
6849
6850 if( nTries==1 ){
6851 conchModTime = buf.st_mtimespec;
6852 usleep(500000); /* wait 0.5 sec and try the lock again*/
6853 continue;
6854 }
6855
6856 assert( nTries>1 );
6857 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6858 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6859 return SQLITE_BUSY;
6860 }
6861
6862 if( nTries==2 ){
6863 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006864 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006865 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006866 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006867 return SQLITE_IOERR_LOCK;
6868 }
6869 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6870 /* don't break the lock if the host id doesn't match */
6871 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6872 return SQLITE_BUSY;
6873 }
6874 }else{
6875 /* don't break the lock on short read or a version mismatch */
6876 return SQLITE_BUSY;
6877 }
6878 usleep(10000000); /* wait 10 sec and try the lock again */
6879 continue;
6880 }
6881
6882 assert( nTries==3 );
6883 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6884 rc = SQLITE_OK;
6885 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006886 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006887 }
6888 if( !rc ){
6889 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6890 }
6891 }
6892 }
6893 } while( rc==SQLITE_BUSY && nTries<3 );
6894
6895 return rc;
6896}
6897
6898/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006899** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6900** lockPath means that the lockPath in the conch file will be used if the
6901** host IDs match, or a new lock path will be generated automatically
6902** and written to the conch file.
6903*/
6904static int proxyTakeConch(unixFile *pFile){
6905 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6906
drh7ed97b92010-01-20 13:07:21 +00006907 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006908 return SQLITE_OK;
6909 }else{
6910 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006911 uuid_t myHostID;
6912 int pError = 0;
6913 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006914 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006915 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006916 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006917 int createConch = 0;
6918 int hostIdMatch = 0;
6919 int readLen = 0;
6920 int tryOldLockPath = 0;
6921 int forceNewLockPath = 0;
6922
drh308c2a52010-05-14 11:30:18 +00006923 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006924 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006925 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006926
drh7ed97b92010-01-20 13:07:21 +00006927 rc = proxyGetHostID(myHostID, &pError);
6928 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006929 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006930 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006931 }
drh7ed97b92010-01-20 13:07:21 +00006932 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006933 if( rc!=SQLITE_OK ){
6934 goto end_takeconch;
6935 }
drh7ed97b92010-01-20 13:07:21 +00006936 /* read the existing conch file */
6937 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6938 if( readLen<0 ){
6939 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006940 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006941 rc = SQLITE_IOERR_READ;
6942 goto end_takeconch;
6943 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6944 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6945 /* a short read or version format mismatch means we need to create a new
6946 ** conch file.
6947 */
6948 createConch = 1;
6949 }
6950 /* if the host id matches and the lock path already exists in the conch
6951 ** we'll try to use the path there, if we can't open that path, we'll
6952 ** retry with a new auto-generated path
6953 */
6954 do { /* in case we need to try again for an :auto: named lock file */
6955
6956 if( !createConch && !forceNewLockPath ){
6957 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6958 PROXY_HOSTIDLEN);
6959 /* if the conch has data compare the contents */
6960 if( !pCtx->lockProxyPath ){
6961 /* for auto-named local lock file, just check the host ID and we'll
6962 ** use the local lock file path that's already in there
6963 */
6964 if( hostIdMatch ){
6965 size_t pathLen = (readLen - PROXY_PATHINDEX);
6966
6967 if( pathLen>=MAXPATHLEN ){
6968 pathLen=MAXPATHLEN-1;
6969 }
6970 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6971 lockPath[pathLen] = 0;
6972 tempLockPath = lockPath;
6973 tryOldLockPath = 1;
6974 /* create a copy of the lock path if the conch is taken */
6975 goto end_takeconch;
6976 }
6977 }else if( hostIdMatch
6978 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6979 readLen-PROXY_PATHINDEX)
6980 ){
6981 /* conch host and lock path match */
6982 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006983 }
drh7ed97b92010-01-20 13:07:21 +00006984 }
6985
6986 /* if the conch isn't writable and doesn't match, we can't take it */
6987 if( (conchFile->openFlags&O_RDWR) == 0 ){
6988 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006989 goto end_takeconch;
6990 }
drh7ed97b92010-01-20 13:07:21 +00006991
6992 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006993 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006994 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6995 tempLockPath = lockPath;
6996 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006997 }
drh7ed97b92010-01-20 13:07:21 +00006998
6999 /* update conch with host and path (this will fail if other process
7000 ** has a shared lock already), if the host id matches, use the big
7001 ** stick.
drh715ff302008-12-03 22:32:44 +00007002 */
drh7ed97b92010-01-20 13:07:21 +00007003 futimes(conchFile->h, NULL);
7004 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007005 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007006 /* We are trying for an exclusive lock but another thread in this
7007 ** same process is still holding a shared lock. */
7008 rc = SQLITE_BUSY;
7009 } else {
7010 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007011 }
drh715ff302008-12-03 22:32:44 +00007012 }else{
drh4bf66fd2015-02-19 02:43:02 +00007013 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007014 }
drh7ed97b92010-01-20 13:07:21 +00007015 if( rc==SQLITE_OK ){
7016 char writeBuffer[PROXY_MAXCONCHLEN];
7017 int writeSize = 0;
7018
7019 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7020 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7021 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007022 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7023 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007024 }else{
7025 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7026 }
7027 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007028 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007029 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007030 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007031 /* If we created a new conch file (not just updated the contents of a
7032 ** valid conch file), try to match the permissions of the database
7033 */
7034 if( rc==SQLITE_OK && createConch ){
7035 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007036 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007037 if( err==0 ){
7038 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7039 S_IROTH|S_IWOTH);
7040 /* try to match the database file R/W permissions, ignore failure */
7041#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007042 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007043#else
drhff812312011-02-23 13:33:46 +00007044 do{
drhe562be52011-03-02 18:01:10 +00007045 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007046 }while( rc==(-1) && errno==EINTR );
7047 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007048 int code = errno;
7049 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7050 cmode, code, strerror(code));
7051 } else {
7052 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7053 }
7054 }else{
7055 int code = errno;
7056 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7057 err, code, strerror(code));
7058#endif
7059 }
drh715ff302008-12-03 22:32:44 +00007060 }
7061 }
drh7ed97b92010-01-20 13:07:21 +00007062 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7063
7064 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007065 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007066 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007067 int fd;
drh7ed97b92010-01-20 13:07:21 +00007068 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007069 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007070 }
7071 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007072 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007073 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007074 if( fd>=0 ){
7075 pFile->h = fd;
7076 }else{
drh9978c972010-02-23 17:36:32 +00007077 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007078 during locking */
7079 }
7080 }
7081 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7082 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7083 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7084 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7085 /* we couldn't create the proxy lock file with the old lock file path
7086 ** so try again via auto-naming
7087 */
7088 forceNewLockPath = 1;
7089 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007090 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007091 }
7092 }
7093 if( rc==SQLITE_OK ){
7094 /* Need to make a copy of path if we extracted the value
7095 ** from the conch file or the path was allocated on the stack
7096 */
7097 if( tempLockPath ){
7098 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7099 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007100 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007101 }
7102 }
7103 }
7104 if( rc==SQLITE_OK ){
7105 pCtx->conchHeld = 1;
7106
7107 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7108 afpLockingContext *afpCtx;
7109 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7110 afpCtx->dbPath = pCtx->lockProxyPath;
7111 }
7112 } else {
7113 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7114 }
drh308c2a52010-05-14 11:30:18 +00007115 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7116 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007117 return rc;
drh308c2a52010-05-14 11:30:18 +00007118 } while (1); /* in case we need to retry the :auto: lock file -
7119 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007120 }
7121}
7122
7123/*
7124** If pFile holds a lock on a conch file, then release that lock.
7125*/
7126static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007127 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007128 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7129 unixFile *conchFile; /* Name of the conch file */
7130
7131 pCtx = (proxyLockingContext *)pFile->lockingContext;
7132 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007133 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007134 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007135 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007136 if( pCtx->conchHeld>0 ){
7137 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7138 }
drh715ff302008-12-03 22:32:44 +00007139 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007140 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7141 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007142 return rc;
7143}
7144
7145/*
7146** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007147** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007148** Make *pConchPath point to the new name. Return SQLITE_OK on success
7149** or SQLITE_NOMEM if unable to obtain memory.
7150**
7151** The caller is responsible for ensuring that the allocated memory
7152** space is eventually freed.
7153**
7154** *pConchPath is set to NULL if a memory allocation error occurs.
7155*/
7156static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7157 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007158 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007159 char *conchPath; /* buffer in which to construct conch name */
7160
7161 /* Allocate space for the conch filename and initialize the name to
7162 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007163 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007164 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007165 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007166 }
7167 memcpy(conchPath, dbPath, len+1);
7168
7169 /* now insert a "." before the last / character */
7170 for( i=(len-1); i>=0; i-- ){
7171 if( conchPath[i]=='/' ){
7172 i++;
7173 break;
7174 }
7175 }
7176 conchPath[i]='.';
7177 while ( i<len ){
7178 conchPath[i+1]=dbPath[i];
7179 i++;
7180 }
7181
7182 /* append the "-conch" suffix to the file */
7183 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007184 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007185
7186 return SQLITE_OK;
7187}
7188
7189
7190/* Takes a fully configured proxy locking-style unix file and switches
7191** the local lock file path
7192*/
7193static int switchLockProxyPath(unixFile *pFile, const char *path) {
7194 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7195 char *oldPath = pCtx->lockProxyPath;
7196 int rc = SQLITE_OK;
7197
drh308c2a52010-05-14 11:30:18 +00007198 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007199 return SQLITE_BUSY;
7200 }
7201
7202 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7203 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7204 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7205 return SQLITE_OK;
7206 }else{
7207 unixFile *lockProxy = pCtx->lockProxy;
7208 pCtx->lockProxy=NULL;
7209 pCtx->conchHeld = 0;
7210 if( lockProxy!=NULL ){
7211 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7212 if( rc ) return rc;
7213 sqlite3_free(lockProxy);
7214 }
7215 sqlite3_free(oldPath);
7216 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7217 }
7218
7219 return rc;
7220}
7221
7222/*
7223** pFile is a file that has been opened by a prior xOpen call. dbPath
7224** is a string buffer at least MAXPATHLEN+1 characters in size.
7225**
7226** This routine find the filename associated with pFile and writes it
7227** int dbPath.
7228*/
7229static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007230#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007231 if( pFile->pMethod == &afpIoMethods ){
7232 /* afp style keeps a reference to the db path in the filePath field
7233 ** of the struct */
drhea678832008-12-10 19:26:22 +00007234 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007235 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7236 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007237 } else
drh715ff302008-12-03 22:32:44 +00007238#endif
7239 if( pFile->pMethod == &dotlockIoMethods ){
7240 /* dot lock style uses the locking context to store the dot lock
7241 ** file path */
7242 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7243 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7244 }else{
7245 /* all other styles use the locking context to store the db file path */
7246 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007247 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007248 }
7249 return SQLITE_OK;
7250}
7251
7252/*
7253** Takes an already filled in unix file and alters it so all file locking
7254** will be performed on the local proxy lock file. The following fields
7255** are preserved in the locking context so that they can be restored and
7256** the unix structure properly cleaned up at close time:
7257** ->lockingContext
7258** ->pMethod
7259*/
7260static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7261 proxyLockingContext *pCtx;
7262 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7263 char *lockPath=NULL;
7264 int rc = SQLITE_OK;
7265
drh308c2a52010-05-14 11:30:18 +00007266 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007267 return SQLITE_BUSY;
7268 }
7269 proxyGetDbPathForUnixFile(pFile, dbPath);
7270 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7271 lockPath=NULL;
7272 }else{
7273 lockPath=(char *)path;
7274 }
7275
drh308c2a52010-05-14 11:30:18 +00007276 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007277 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007278
drhf3cdcdc2015-04-29 16:50:28 +00007279 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007280 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007281 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007282 }
7283 memset(pCtx, 0, sizeof(*pCtx));
7284
7285 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7286 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007287 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7288 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7289 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7290 ** (c) the file system is read-only, then enable no-locking access.
7291 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7292 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7293 */
7294 struct statfs fsInfo;
7295 struct stat conchInfo;
7296 int goLockless = 0;
7297
drh99ab3b12011-03-02 15:09:07 +00007298 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007299 int err = errno;
7300 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7301 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7302 }
7303 }
7304 if( goLockless ){
7305 pCtx->conchHeld = -1; /* read only FS/ lockless */
7306 rc = SQLITE_OK;
7307 }
7308 }
drh715ff302008-12-03 22:32:44 +00007309 }
7310 if( rc==SQLITE_OK && lockPath ){
7311 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7312 }
7313
7314 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007315 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7316 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007317 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007318 }
7319 }
7320 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007321 /* all memory is allocated, proxys are created and assigned,
7322 ** switch the locking context and pMethod then return.
7323 */
drh715ff302008-12-03 22:32:44 +00007324 pCtx->oldLockingContext = pFile->lockingContext;
7325 pFile->lockingContext = pCtx;
7326 pCtx->pOldMethod = pFile->pMethod;
7327 pFile->pMethod = &proxyIoMethods;
7328 }else{
7329 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007330 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007331 sqlite3_free(pCtx->conchFile);
7332 }
drhd56b1212010-08-11 06:14:15 +00007333 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007334 sqlite3_free(pCtx->conchFilePath);
7335 sqlite3_free(pCtx);
7336 }
drh308c2a52010-05-14 11:30:18 +00007337 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7338 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007339 return rc;
7340}
7341
7342
7343/*
7344** This routine handles sqlite3_file_control() calls that are specific
7345** to proxy locking.
7346*/
7347static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7348 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007349 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007350 unixFile *pFile = (unixFile*)id;
7351 if( pFile->pMethod == &proxyIoMethods ){
7352 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7353 proxyTakeConch(pFile);
7354 if( pCtx->lockProxyPath ){
7355 *(const char **)pArg = pCtx->lockProxyPath;
7356 }else{
7357 *(const char **)pArg = ":auto: (not held)";
7358 }
7359 } else {
7360 *(const char **)pArg = NULL;
7361 }
7362 return SQLITE_OK;
7363 }
drh4bf66fd2015-02-19 02:43:02 +00007364 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007365 unixFile *pFile = (unixFile*)id;
7366 int rc = SQLITE_OK;
7367 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7368 if( pArg==NULL || (const char *)pArg==0 ){
7369 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007370 /* turn off proxy locking - not supported. If support is added for
7371 ** switching proxy locking mode off then it will need to fail if
7372 ** the journal mode is WAL mode.
7373 */
drh715ff302008-12-03 22:32:44 +00007374 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7375 }else{
7376 /* turn off proxy locking - already off - NOOP */
7377 rc = SQLITE_OK;
7378 }
7379 }else{
7380 const char *proxyPath = (const char *)pArg;
7381 if( isProxyStyle ){
7382 proxyLockingContext *pCtx =
7383 (proxyLockingContext*)pFile->lockingContext;
7384 if( !strcmp(pArg, ":auto:")
7385 || (pCtx->lockProxyPath &&
7386 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7387 ){
7388 rc = SQLITE_OK;
7389 }else{
7390 rc = switchLockProxyPath(pFile, proxyPath);
7391 }
7392 }else{
7393 /* turn on proxy file locking */
7394 rc = proxyTransformUnixFile(pFile, proxyPath);
7395 }
7396 }
7397 return rc;
7398 }
7399 default: {
7400 assert( 0 ); /* The call assures that only valid opcodes are sent */
7401 }
7402 }
7403 /*NOTREACHED*/
7404 return SQLITE_ERROR;
7405}
7406
7407/*
7408** Within this division (the proxying locking implementation) the procedures
7409** above this point are all utilities. The lock-related methods of the
7410** proxy-locking sqlite3_io_method object follow.
7411*/
7412
7413
7414/*
7415** This routine checks if there is a RESERVED lock held on the specified
7416** file by this or any other process. If such a lock is held, set *pResOut
7417** to a non-zero value otherwise *pResOut is set to zero. The return value
7418** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7419*/
7420static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7421 unixFile *pFile = (unixFile*)id;
7422 int rc = proxyTakeConch(pFile);
7423 if( rc==SQLITE_OK ){
7424 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007425 if( pCtx->conchHeld>0 ){
7426 unixFile *proxy = pCtx->lockProxy;
7427 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7428 }else{ /* conchHeld < 0 is lockless */
7429 pResOut=0;
7430 }
drh715ff302008-12-03 22:32:44 +00007431 }
7432 return rc;
7433}
7434
7435/*
drh308c2a52010-05-14 11:30:18 +00007436** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007437** of the following:
7438**
7439** (1) SHARED_LOCK
7440** (2) RESERVED_LOCK
7441** (3) PENDING_LOCK
7442** (4) EXCLUSIVE_LOCK
7443**
7444** Sometimes when requesting one lock state, additional lock states
7445** are inserted in between. The locking might fail on one of the later
7446** transitions leaving the lock state different from what it started but
7447** still short of its goal. The following chart shows the allowed
7448** transitions and the inserted intermediate states:
7449**
7450** UNLOCKED -> SHARED
7451** SHARED -> RESERVED
7452** SHARED -> (PENDING) -> EXCLUSIVE
7453** RESERVED -> (PENDING) -> EXCLUSIVE
7454** PENDING -> EXCLUSIVE
7455**
7456** This routine will only increase a lock. Use the sqlite3OsUnlock()
7457** routine to lower a locking level.
7458*/
drh308c2a52010-05-14 11:30:18 +00007459static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007460 unixFile *pFile = (unixFile*)id;
7461 int rc = proxyTakeConch(pFile);
7462 if( rc==SQLITE_OK ){
7463 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007464 if( pCtx->conchHeld>0 ){
7465 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007466 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7467 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007468 }else{
7469 /* conchHeld < 0 is lockless */
7470 }
drh715ff302008-12-03 22:32:44 +00007471 }
7472 return rc;
7473}
7474
7475
7476/*
drh308c2a52010-05-14 11:30:18 +00007477** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007478** must be either NO_LOCK or SHARED_LOCK.
7479**
7480** If the locking level of the file descriptor is already at or below
7481** the requested locking level, this routine is a no-op.
7482*/
drh308c2a52010-05-14 11:30:18 +00007483static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007484 unixFile *pFile = (unixFile*)id;
7485 int rc = proxyTakeConch(pFile);
7486 if( rc==SQLITE_OK ){
7487 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007488 if( pCtx->conchHeld>0 ){
7489 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007490 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7491 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007492 }else{
7493 /* conchHeld < 0 is lockless */
7494 }
drh715ff302008-12-03 22:32:44 +00007495 }
7496 return rc;
7497}
7498
7499/*
7500** Close a file that uses proxy locks.
7501*/
7502static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007503 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007504 unixFile *pFile = (unixFile*)id;
7505 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7506 unixFile *lockProxy = pCtx->lockProxy;
7507 unixFile *conchFile = pCtx->conchFile;
7508 int rc = SQLITE_OK;
7509
7510 if( lockProxy ){
7511 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7512 if( rc ) return rc;
7513 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7514 if( rc ) return rc;
7515 sqlite3_free(lockProxy);
7516 pCtx->lockProxy = 0;
7517 }
7518 if( conchFile ){
7519 if( pCtx->conchHeld ){
7520 rc = proxyReleaseConch(pFile);
7521 if( rc ) return rc;
7522 }
7523 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7524 if( rc ) return rc;
7525 sqlite3_free(conchFile);
7526 }
drhd56b1212010-08-11 06:14:15 +00007527 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007528 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007529 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007530 /* restore the original locking context and pMethod then close it */
7531 pFile->lockingContext = pCtx->oldLockingContext;
7532 pFile->pMethod = pCtx->pOldMethod;
7533 sqlite3_free(pCtx);
7534 return pFile->pMethod->xClose(id);
7535 }
7536 return SQLITE_OK;
7537}
7538
7539
7540
drhd2cb50b2009-01-09 21:41:17 +00007541#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007542/*
7543** The proxy locking style is intended for use with AFP filesystems.
7544** And since AFP is only supported on MacOSX, the proxy locking is also
7545** restricted to MacOSX.
7546**
7547**
7548******************* End of the proxy lock implementation **********************
7549******************************************************************************/
7550
drh734c9862008-11-28 15:37:20 +00007551/*
danielk1977e339d652008-06-28 11:23:00 +00007552** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007553**
7554** This routine registers all VFS implementations for unix-like operating
7555** systems. This routine, and the sqlite3_os_end() routine that follows,
7556** should be the only routines in this file that are visible from other
7557** files.
drh6b9d6dd2008-12-03 19:34:47 +00007558**
7559** This routine is called once during SQLite initialization and by a
7560** single thread. The memory allocation and mutex subsystems have not
7561** necessarily been initialized when this routine is called, and so they
7562** should not be used.
drh153c62c2007-08-24 03:51:33 +00007563*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007564int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007565 /*
7566 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007567 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7568 ** to the "finder" function. (pAppData is a pointer to a pointer because
7569 ** silly C90 rules prohibit a void* from being cast to a function pointer
7570 ** and so we have to go through the intermediate pointer to avoid problems
7571 ** when compiling with -pedantic-errors on GCC.)
7572 **
7573 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007574 ** finder-function. The finder-function returns a pointer to the
7575 ** sqlite_io_methods object that implements the desired locking
7576 ** behaviors. See the division above that contains the IOMETHODS
7577 ** macro for addition information on finder-functions.
7578 **
7579 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7580 ** object. But the "autolockIoFinder" available on MacOSX does a little
7581 ** more than that; it looks at the filesystem type that hosts the
7582 ** database file and tries to choose an locking method appropriate for
7583 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007584 */
drh7708e972008-11-29 00:56:52 +00007585 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007586 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007587 sizeof(unixFile), /* szOsFile */ \
7588 MAX_PATHNAME, /* mxPathname */ \
7589 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007590 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007591 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007592 unixOpen, /* xOpen */ \
7593 unixDelete, /* xDelete */ \
7594 unixAccess, /* xAccess */ \
7595 unixFullPathname, /* xFullPathname */ \
7596 unixDlOpen, /* xDlOpen */ \
7597 unixDlError, /* xDlError */ \
7598 unixDlSym, /* xDlSym */ \
7599 unixDlClose, /* xDlClose */ \
7600 unixRandomness, /* xRandomness */ \
7601 unixSleep, /* xSleep */ \
7602 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007603 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007604 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007605 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007606 unixGetSystemCall, /* xGetSystemCall */ \
7607 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007608 }
7609
drh6b9d6dd2008-12-03 19:34:47 +00007610 /*
7611 ** All default VFSes for unix are contained in the following array.
7612 **
7613 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7614 ** by the SQLite core when the VFS is registered. So the following
7615 ** array cannot be const.
7616 */
danielk1977e339d652008-06-28 11:23:00 +00007617 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007618#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007619 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007620#elif OS_VXWORKS
7621 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007622#else
7623 UNIXVFS("unix", posixIoFinder ),
7624#endif
7625 UNIXVFS("unix-none", nolockIoFinder ),
7626 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007627 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007628#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007629 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007630#endif
drhe89b2912015-03-03 20:42:01 +00007631#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007632 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007633#endif
drhe89b2912015-03-03 20:42:01 +00007634#if SQLITE_ENABLE_LOCKING_STYLE
7635 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007636#endif
drhd2cb50b2009-01-09 21:41:17 +00007637#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007638 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007639 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007640 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007641#endif
drh153c62c2007-08-24 03:51:33 +00007642 };
drh6b9d6dd2008-12-03 19:34:47 +00007643 unsigned int i; /* Loop counter */
7644
drh2aa5a002011-04-13 13:42:25 +00007645 /* Double-check that the aSyscall[] array has been constructed
7646 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007647 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007648
drh6b9d6dd2008-12-03 19:34:47 +00007649 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007650 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007651 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007652 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007653 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007654}
danielk1977e339d652008-06-28 11:23:00 +00007655
7656/*
drh6b9d6dd2008-12-03 19:34:47 +00007657** Shutdown the operating system interface.
7658**
7659** Some operating systems might need to do some cleanup in this routine,
7660** to release dynamically allocated objects. But not on unix.
7661** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007662*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007663int sqlite3_os_end(void){
7664 return SQLITE_OK;
7665}
drhdce8bdb2007-08-16 13:01:44 +00007666
danielk197729bafea2008-06-26 10:41:19 +00007667#endif /* SQLITE_OS_UNIX */