blob: 8dfbe6181406e2b6a7e4b3086a87ca1e017d2d89 [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
drh6033e152012-11-13 11:08:49 +000049/* Use posix_fallocate() if it is available
50*/
51#if !defined(HAVE_POSIX_FALLOCATE) \
52 && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
53# define HAVE_POSIX_FALLOCATE 1
54#endif
55
danielk1977e339d652008-06-28 11:23:00 +000056/*
drh6b9d6dd2008-12-03 19:34:47 +000057** There are various methods for file locking used for concurrency
58** control:
danielk1977e339d652008-06-28 11:23:00 +000059**
drh734c9862008-11-28 15:37:20 +000060** 1. POSIX locking (the default),
61** 2. No locking,
62** 3. Dot-file locking,
63** 4. flock() locking,
64** 5. AFP locking (OSX only),
65** 6. Named POSIX semaphores (VXWorks only),
66** 7. proxy locking. (OSX only)
67**
68** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
69** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
70** selection of the appropriate locking style based on the filesystem
71** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000072*/
drh40bbb0a2008-09-23 10:23:26 +000073#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000074# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000075# define SQLITE_ENABLE_LOCKING_STYLE 1
76# else
77# define SQLITE_ENABLE_LOCKING_STYLE 0
78# endif
79#endif
drhbfe66312006-10-03 17:40:40 +000080
drh9cbe6352005-11-29 03:13:21 +000081/*
drh6c7d5c52008-11-21 20:32:33 +000082** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000083** vxworks, or 0 otherwise.
84*/
drh6c7d5c52008-11-21 20:32:33 +000085#ifndef OS_VXWORKS
86# if defined(__RTP__) || defined(_WRS_KERNEL)
87# define OS_VXWORKS 1
88# else
89# define OS_VXWORKS 0
90# endif
danielk1977397d65f2008-11-19 11:35:39 +000091#endif
92
93/*
drh9cbe6352005-11-29 03:13:21 +000094** These #defines should enable >2GB file support on Posix if the
95** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000096** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000097**
98** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
99** on the compiler command line. This is necessary if you are compiling
100** on a recent machine (ex: RedHat 7.2) but you want your code to work
101** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
102** without this option, LFS is enable. But LFS does not exist in the kernel
103** in RedHat 6.0, so the code won't work. Hence, for maximum binary
104** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +0000105**
106** The previous paragraph was written in 2005. (This paragraph is written
107** on 2008-11-28.) These days, all Linux kernels support large files, so
108** you should probably leave LFS enabled. But some embedded platforms might
109** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000110*/
111#ifndef SQLITE_DISABLE_LFS
112# define _LARGE_FILE 1
113# ifndef _FILE_OFFSET_BITS
114# define _FILE_OFFSET_BITS 64
115# endif
116# define _LARGEFILE_SOURCE 1
117#endif
drhbbd42a62004-05-22 17:41:58 +0000118
drh9cbe6352005-11-29 03:13:21 +0000119/*
120** standard include files.
121*/
122#include <sys/types.h>
123#include <sys/stat.h>
124#include <fcntl.h>
125#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000126#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000127#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000128#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000129#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000130#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000131#endif
drh1da88f02011-12-17 16:09:16 +0000132
danielk1977e339d652008-06-28 11:23:00 +0000133
drh40bbb0a2008-09-23 10:23:26 +0000134#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000135# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000136# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000137# include <semaphore.h>
138# include <limits.h>
139# else
drh9b35ea62008-11-29 02:20:26 +0000140# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000141# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000142# endif
drhbfe66312006-10-03 17:40:40 +0000143#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000144
drhf8b4d8c2010-03-05 13:53:22 +0000145#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000146# include <sys/mount.h>
147#endif
148
drhdbe4b882011-06-20 18:00:17 +0000149#ifdef HAVE_UTIME
150# include <utime.h>
151#endif
152
drh9cbe6352005-11-29 03:13:21 +0000153/*
drh7ed97b92010-01-20 13:07:21 +0000154** Allowed values of unixFile.fsFlags
155*/
156#define SQLITE_FSFLAGS_IS_MSDOS 0x1
157
158/*
drhf1a221e2006-01-15 17:27:17 +0000159** If we are to be thread-safe, include the pthreads header and define
160** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000161*/
drhd677b3d2007-08-20 22:48:41 +0000162#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000163# include <pthread.h>
164# define SQLITE_UNIX_THREADS 1
165#endif
166
167/*
168** Default permissions when creating a new file
169*/
170#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
171# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
172#endif
173
danielk1977b4b47412007-08-17 15:53:36 +0000174/*
drh5adc60b2012-04-14 13:25:11 +0000175** Default permissions when creating auto proxy dir
176*/
aswiftaebf4132008-11-21 00:10:35 +0000177#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
178# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
179#endif
180
181/*
danielk1977b4b47412007-08-17 15:53:36 +0000182** Maximum supported path-length.
183*/
184#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000185
drh734c9862008-11-28 15:37:20 +0000186/*
drh734c9862008-11-28 15:37:20 +0000187** Only set the lastErrno if the error code is a real error and not
188** a normal expected return code of SQLITE_BUSY or SQLITE_OK
189*/
190#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
191
drhd91c68f2010-05-14 14:52:25 +0000192/* Forward references */
193typedef struct unixShm unixShm; /* Connection shared memory */
194typedef struct unixShmNode unixShmNode; /* Shared memory instance */
195typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
196typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000197
198/*
dane946c392009-08-22 11:39:46 +0000199** Sometimes, after a file handle is closed by SQLite, the file descriptor
200** cannot be closed immediately. In these cases, instances of the following
201** structure are used to store the file descriptor while waiting for an
202** opportunity to either close or reuse it.
203*/
dane946c392009-08-22 11:39:46 +0000204struct UnixUnusedFd {
205 int fd; /* File descriptor to close */
206 int flags; /* Flags this file descriptor was opened with */
207 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
208};
209
210/*
drh9b35ea62008-11-29 02:20:26 +0000211** The unixFile structure is subclass of sqlite3_file specific to the unix
212** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000213*/
drh054889e2005-11-30 03:20:31 +0000214typedef struct unixFile unixFile;
215struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000216 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000217 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000218 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000219 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000220 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000221 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000222 int lastErrno; /* The unix errno from last I/O error */
223 void *lockingContext; /* Locking style specific state */
224 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000225 const char *zPath; /* Name of the file */
226 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000227 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh0d0614b2013-03-25 23:09:28 +0000228 int nFetchOut; /* Number of outstanding xFetch refs */
229 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000230 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
231 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000232 void *pMapRegion; /* Memory mapped region */
drh537dddf2012-10-26 13:46:24 +0000233#ifdef __QNXNTO__
234 int sectorSize; /* Device sector size */
235 int deviceCharacteristics; /* Precomputed device characteristics */
236#endif
drh08c6d442009-02-09 17:34:07 +0000237#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000238 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000239#endif
drh7ed97b92010-01-20 13:07:21 +0000240#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000241 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000242#endif
243#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000244 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000245#endif
drhd3d8c042012-05-29 17:02:40 +0000246#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000247 /* The next group of variables are used to track whether or not the
248 ** transaction counter in bytes 24-27 of database files are updated
249 ** whenever any part of the database changes. An assertion fault will
250 ** occur if a file is updated without also updating the transaction
251 ** counter. This test is made to avoid new problems similar to the
252 ** one described by ticket #3584.
253 */
254 unsigned char transCntrChng; /* True if the transaction counter changed */
255 unsigned char dbUpdate; /* True if any part of database file changed */
256 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000257
drh8f941bc2009-01-14 23:03:40 +0000258#endif
danf23da962013-03-23 21:00:41 +0000259
danielk1977967a4a12007-08-20 14:23:44 +0000260#ifdef SQLITE_TEST
261 /* In test mode, increase the size of this structure a bit so that
262 ** it is larger than the struct CrashFile defined in test6.c.
263 */
264 char aPadding[32];
265#endif
drh9cbe6352005-11-29 03:13:21 +0000266};
267
drh0ccebe72005-06-07 22:22:50 +0000268/*
drha7e61d82011-03-12 17:02:57 +0000269** Allowed values for the unixFile.ctrlFlags bitmask:
270*/
drhf0b190d2011-07-26 16:03:07 +0000271#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
272#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
273#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000274#ifndef SQLITE_DISABLE_DIRSYNC
275# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
276#else
277# define UNIXFILE_DIRSYNC 0x00
278#endif
drhcb15f352011-12-23 01:04:17 +0000279#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000280#define UNIXFILE_DELETE 0x20 /* Delete on close */
281#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
282#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhfbc7e882013-04-11 01:16:15 +0000283#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
drha7e61d82011-03-12 17:02:57 +0000284
285/*
drh198bf392006-01-06 21:52:49 +0000286** Include code that is common to all os_*.c files
287*/
288#include "os_common.h"
289
290/*
drh0ccebe72005-06-07 22:22:50 +0000291** Define various macros that are missing from some systems.
292*/
drhbbd42a62004-05-22 17:41:58 +0000293#ifndef O_LARGEFILE
294# define O_LARGEFILE 0
295#endif
296#ifdef SQLITE_DISABLE_LFS
297# undef O_LARGEFILE
298# define O_LARGEFILE 0
299#endif
300#ifndef O_NOFOLLOW
301# define O_NOFOLLOW 0
302#endif
303#ifndef O_BINARY
304# define O_BINARY 0
305#endif
306
307/*
drh2b4b5962005-06-15 17:47:55 +0000308** The threadid macro resolves to the thread-id or to 0. Used for
309** testing and debugging only.
310*/
drhd677b3d2007-08-20 22:48:41 +0000311#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000312#define threadid pthread_self()
313#else
314#define threadid 0
315#endif
316
drh99ab3b12011-03-02 15:09:07 +0000317/*
dane6ecd662013-04-01 17:56:59 +0000318** HAVE_MREMAP defaults to true on Linux and false everywhere else.
319*/
320#if !defined(HAVE_MREMAP)
321# if defined(__linux__) && defined(_GNU_SOURCE)
322# define HAVE_MREMAP 1
323# else
324# define HAVE_MREMAP 0
325# endif
326#endif
327
328/*
drh9a3baf12011-04-25 18:01:27 +0000329** Different Unix systems declare open() in different ways. Same use
330** open(const char*,int,mode_t). Others use open(const char*,int,...).
331** The difference is important when using a pointer to the function.
332**
333** The safest way to deal with the problem is to always use this wrapper
334** which always has the same well-defined interface.
335*/
336static int posixOpen(const char *zFile, int flags, int mode){
337 return open(zFile, flags, mode);
338}
339
drhed466822012-05-31 13:10:49 +0000340/*
341** On some systems, calls to fchown() will trigger a message in a security
342** log if they come from non-root processes. So avoid calling fchown() if
343** we are not running as root.
344*/
345static int posixFchown(int fd, uid_t uid, gid_t gid){
346 return geteuid() ? 0 : fchown(fd,uid,gid);
347}
348
drh90315a22011-08-10 01:52:12 +0000349/* Forward reference */
350static int openDirectory(const char*, int*);
351
drh9a3baf12011-04-25 18:01:27 +0000352/*
drh99ab3b12011-03-02 15:09:07 +0000353** Many system calls are accessed through pointer-to-functions so that
354** they may be overridden at runtime to facilitate fault injection during
355** testing and sandboxing. The following array holds the names and pointers
356** to all overrideable system calls.
357*/
358static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000359 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000360 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
361 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000362} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000363 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
364#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000365
drh58ad5802011-03-23 22:02:23 +0000366 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000367#define osClose ((int(*)(int))aSyscall[1].pCurrent)
368
drh58ad5802011-03-23 22:02:23 +0000369 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000370#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
371
drh58ad5802011-03-23 22:02:23 +0000372 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000373#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
374
drh58ad5802011-03-23 22:02:23 +0000375 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000376#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
377
378/*
379** The DJGPP compiler environment looks mostly like Unix, but it
380** lacks the fcntl() system call. So redefine fcntl() to be something
381** that always succeeds. This means that locking does not occur under
382** DJGPP. But it is DOS - what did you expect?
383*/
384#ifdef __DJGPP__
385 { "fstat", 0, 0 },
386#define osFstat(a,b,c) 0
387#else
drh58ad5802011-03-23 22:02:23 +0000388 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000389#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
390#endif
391
drh58ad5802011-03-23 22:02:23 +0000392 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000393#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
394
drh58ad5802011-03-23 22:02:23 +0000395 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000396#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000397
drh58ad5802011-03-23 22:02:23 +0000398 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000399#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
400
drhd4a80312011-04-15 14:33:20 +0000401#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000402 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000403#else
drh58ad5802011-03-23 22:02:23 +0000404 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000405#endif
406#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
407
408#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000409 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000410#else
drh58ad5802011-03-23 22:02:23 +0000411 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000412#endif
413#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
414
drh58ad5802011-03-23 22:02:23 +0000415 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000416#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
417
drhd4a80312011-04-15 14:33:20 +0000418#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000419 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000420#else
drh58ad5802011-03-23 22:02:23 +0000421 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000422#endif
423#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
424 aSyscall[12].pCurrent)
425
426#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000427 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000428#else
drh58ad5802011-03-23 22:02:23 +0000429 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000430#endif
431#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
432 aSyscall[13].pCurrent)
433
drh58ad5802011-03-23 22:02:23 +0000434 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000435#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000436
437#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000438 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000439#else
drh58ad5802011-03-23 22:02:23 +0000440 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000441#endif
dan0fd7d862011-03-29 10:04:23 +0000442#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000443
drh036ac7f2011-08-08 23:18:05 +0000444 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
445#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
446
drh90315a22011-08-10 01:52:12 +0000447 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
448#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
449
drh9ef6bc42011-11-04 02:24:02 +0000450 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
451#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
452
453 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
454#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
455
drhed466822012-05-31 13:10:49 +0000456 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000457#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000458
dan893c0ff2013-03-25 19:05:07 +0000459 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
460#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
461
drhd1ab8062013-03-25 20:50:25 +0000462 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
463#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
464
dane6ecd662013-04-01 17:56:59 +0000465#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000466 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
467#else
468 { "mremap", (sqlite3_syscall_ptr)0, 0 },
469#endif
470#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
471
drhe562be52011-03-02 18:01:10 +0000472}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000473
474/*
475** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000476** "unix" VFSes. Return SQLITE_OK opon successfully updating the
477** system call pointer, or SQLITE_NOTFOUND if there is no configurable
478** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000479*/
480static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000481 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
482 const char *zName, /* Name of system call to override */
483 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000484){
drh58ad5802011-03-23 22:02:23 +0000485 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000486 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000487
488 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000489 if( zName==0 ){
490 /* If no zName is given, restore all system calls to their default
491 ** settings and return NULL
492 */
dan51438a72011-04-02 17:00:47 +0000493 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000494 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
495 if( aSyscall[i].pDefault ){
496 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000497 }
498 }
499 }else{
500 /* If zName is specified, operate on only the one system call
501 ** specified.
502 */
503 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
504 if( strcmp(zName, aSyscall[i].zName)==0 ){
505 if( aSyscall[i].pDefault==0 ){
506 aSyscall[i].pDefault = aSyscall[i].pCurrent;
507 }
drh1df30962011-03-02 19:06:42 +0000508 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000509 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
510 aSyscall[i].pCurrent = pNewFunc;
511 break;
512 }
513 }
514 }
515 return rc;
516}
517
drh1df30962011-03-02 19:06:42 +0000518/*
519** Return the value of a system call. Return NULL if zName is not a
520** recognized system call name. NULL is also returned if the system call
521** is currently undefined.
522*/
drh58ad5802011-03-23 22:02:23 +0000523static sqlite3_syscall_ptr unixGetSystemCall(
524 sqlite3_vfs *pNotUsed,
525 const char *zName
526){
527 unsigned int i;
528
529 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000530 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
531 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
532 }
533 return 0;
534}
535
536/*
537** Return the name of the first system call after zName. If zName==NULL
538** then return the name of the first system call. Return NULL if zName
539** is the last system call or if zName is not the name of a valid
540** system call.
541*/
542static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000543 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000544
545 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000546 if( zName ){
547 for(i=0; i<ArraySize(aSyscall)-1; i++){
548 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000549 }
550 }
dan0fd7d862011-03-29 10:04:23 +0000551 for(i++; i<ArraySize(aSyscall); i++){
552 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000553 }
554 return 0;
555}
556
drhad4f1e52011-03-04 15:43:57 +0000557/*
drh8c815d12012-02-13 20:16:37 +0000558** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000559** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000560**
561** If the file creation mode "m" is 0 then set it to the default for
562** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
563** 0644) as modified by the system umask. If m is not 0, then
564** make the file creation mode be exactly m ignoring the umask.
565**
566** The m parameter will be non-zero only when creating -wal, -journal,
567** and -shm files. We want those files to have *exactly* the same
568** permissions as their original database, unadulterated by the umask.
569** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
570** transaction crashes and leaves behind hot journals, then any
571** process that is able to write to the database will also be able to
572** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000573*/
drh8c815d12012-02-13 20:16:37 +0000574static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000575 int fd;
drhe1186ab2013-01-04 20:45:13 +0000576 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5adc60b2012-04-14 13:25:11 +0000577 do{
578#if defined(O_CLOEXEC)
579 fd = osOpen(z,f|O_CLOEXEC,m2);
580#else
581 fd = osOpen(z,f,m2);
582#endif
583 }while( fd<0 && errno==EINTR );
drhe1186ab2013-01-04 20:45:13 +0000584 if( fd>=0 ){
585 if( m!=0 ){
586 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000587 if( osFstat(fd, &statbuf)==0
588 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000589 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000590 ){
drhe1186ab2013-01-04 20:45:13 +0000591 osFchmod(fd, m);
592 }
593 }
drh5adc60b2012-04-14 13:25:11 +0000594#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000595 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000596#endif
drhe1186ab2013-01-04 20:45:13 +0000597 }
drh5adc60b2012-04-14 13:25:11 +0000598 return fd;
drhad4f1e52011-03-04 15:43:57 +0000599}
danielk197713adf8a2004-06-03 16:08:41 +0000600
drh107886a2008-11-21 22:21:50 +0000601/*
dan9359c7b2009-08-21 08:29:10 +0000602** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000603** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000604** vxworksFileId objects used by this file, all of which may be
605** shared by multiple threads.
606**
607** Function unixMutexHeld() is used to assert() that the global mutex
608** is held when required. This function is only used as part of assert()
609** statements. e.g.
610**
611** unixEnterMutex()
612** assert( unixMutexHeld() );
613** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000614*/
615static void unixEnterMutex(void){
616 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
617}
618static void unixLeaveMutex(void){
619 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
620}
dan9359c7b2009-08-21 08:29:10 +0000621#ifdef SQLITE_DEBUG
622static int unixMutexHeld(void) {
623 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
624}
625#endif
drh107886a2008-11-21 22:21:50 +0000626
drh734c9862008-11-28 15:37:20 +0000627
drh30ddce62011-10-15 00:16:30 +0000628#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000629/*
630** Helper function for printing out trace information from debugging
631** binaries. This returns the string represetation of the supplied
632** integer lock-type.
633*/
drh308c2a52010-05-14 11:30:18 +0000634static const char *azFileLock(int eFileLock){
635 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000636 case NO_LOCK: return "NONE";
637 case SHARED_LOCK: return "SHARED";
638 case RESERVED_LOCK: return "RESERVED";
639 case PENDING_LOCK: return "PENDING";
640 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000641 }
642 return "ERROR";
643}
644#endif
645
646#ifdef SQLITE_LOCK_TRACE
647/*
648** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000649**
drh734c9862008-11-28 15:37:20 +0000650** This routine is used for troubleshooting locks on multithreaded
651** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
652** command-line option on the compiler. This code is normally
653** turned off.
654*/
655static int lockTrace(int fd, int op, struct flock *p){
656 char *zOpName, *zType;
657 int s;
658 int savedErrno;
659 if( op==F_GETLK ){
660 zOpName = "GETLK";
661 }else if( op==F_SETLK ){
662 zOpName = "SETLK";
663 }else{
drh99ab3b12011-03-02 15:09:07 +0000664 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000665 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
666 return s;
667 }
668 if( p->l_type==F_RDLCK ){
669 zType = "RDLCK";
670 }else if( p->l_type==F_WRLCK ){
671 zType = "WRLCK";
672 }else if( p->l_type==F_UNLCK ){
673 zType = "UNLCK";
674 }else{
675 assert( 0 );
676 }
677 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000678 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000679 savedErrno = errno;
680 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
681 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
682 (int)p->l_pid, s);
683 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
684 struct flock l2;
685 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000686 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000687 if( l2.l_type==F_RDLCK ){
688 zType = "RDLCK";
689 }else if( l2.l_type==F_WRLCK ){
690 zType = "WRLCK";
691 }else if( l2.l_type==F_UNLCK ){
692 zType = "UNLCK";
693 }else{
694 assert( 0 );
695 }
696 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
697 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
698 }
699 errno = savedErrno;
700 return s;
701}
drh99ab3b12011-03-02 15:09:07 +0000702#undef osFcntl
703#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000704#endif /* SQLITE_LOCK_TRACE */
705
drhff812312011-02-23 13:33:46 +0000706/*
707** Retry ftruncate() calls that fail due to EINTR
708*/
drhff812312011-02-23 13:33:46 +0000709static int robust_ftruncate(int h, sqlite3_int64 sz){
710 int rc;
drh99ab3b12011-03-02 15:09:07 +0000711 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000712 return rc;
713}
drh734c9862008-11-28 15:37:20 +0000714
715/*
716** This routine translates a standard POSIX errno code into something
717** useful to the clients of the sqlite3 functions. Specifically, it is
718** intended to translate a variety of "try again" errors into SQLITE_BUSY
719** and a variety of "please close the file descriptor NOW" errors into
720** SQLITE_IOERR
721**
722** Errors during initialization of locks, or file system support for locks,
723** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
724*/
725static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
726 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000727#if 0
728 /* At one point this code was not commented out. In theory, this branch
729 ** should never be hit, as this function should only be called after
730 ** a locking-related function (i.e. fcntl()) has returned non-zero with
731 ** the value of errno as the first argument. Since a system call has failed,
732 ** errno should be non-zero.
733 **
734 ** Despite this, if errno really is zero, we still don't want to return
735 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
736 ** propagated back to the caller. Commenting this branch out means errno==0
737 ** will be handled by the "default:" case below.
738 */
drh734c9862008-11-28 15:37:20 +0000739 case 0:
740 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000741#endif
742
drh734c9862008-11-28 15:37:20 +0000743 case EAGAIN:
744 case ETIMEDOUT:
745 case EBUSY:
746 case EINTR:
747 case ENOLCK:
748 /* random NFS retry error, unless during file system support
749 * introspection, in which it actually means what it says */
750 return SQLITE_BUSY;
751
752 case EACCES:
753 /* EACCES is like EAGAIN during locking operations, but not any other time*/
754 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000755 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
756 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
757 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000758 return SQLITE_BUSY;
759 }
760 /* else fall through */
761 case EPERM:
762 return SQLITE_PERM;
763
danea83bc62011-04-01 11:56:32 +0000764 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
765 ** this module never makes such a call. And the code in SQLite itself
766 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
767 ** this case is also commented out. If the system does set errno to EDEADLK,
768 ** the default SQLITE_IOERR_XXX code will be returned. */
769#if 0
drh734c9862008-11-28 15:37:20 +0000770 case EDEADLK:
771 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000772#endif
drh734c9862008-11-28 15:37:20 +0000773
774#if EOPNOTSUPP!=ENOTSUP
775 case EOPNOTSUPP:
776 /* something went terribly awry, unless during file system support
777 * introspection, in which it actually means what it says */
778#endif
779#ifdef ENOTSUP
780 case ENOTSUP:
781 /* invalid fd, unless during file system support introspection, in which
782 * it actually means what it says */
783#endif
784 case EIO:
785 case EBADF:
786 case EINVAL:
787 case ENOTCONN:
788 case ENODEV:
789 case ENXIO:
790 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000791#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000792 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000793#endif
drh734c9862008-11-28 15:37:20 +0000794 case ENOSYS:
795 /* these should force the client to close the file and reconnect */
796
797 default:
798 return sqliteIOErr;
799 }
800}
801
802
drh734c9862008-11-28 15:37:20 +0000803/******************************************************************************
804****************** Begin Unique File ID Utility Used By VxWorks ***************
805**
806** On most versions of unix, we can get a unique ID for a file by concatenating
807** the device number and the inode number. But this does not work on VxWorks.
808** On VxWorks, a unique file id must be based on the canonical filename.
809**
810** A pointer to an instance of the following structure can be used as a
811** unique file ID in VxWorks. Each instance of this structure contains
812** a copy of the canonical filename. There is also a reference count.
813** The structure is reclaimed when the number of pointers to it drops to
814** zero.
815**
816** There are never very many files open at one time and lookups are not
817** a performance-critical path, so it is sufficient to put these
818** structures on a linked list.
819*/
820struct vxworksFileId {
821 struct vxworksFileId *pNext; /* Next in a list of them all */
822 int nRef; /* Number of references to this one */
823 int nName; /* Length of the zCanonicalName[] string */
824 char *zCanonicalName; /* Canonical filename */
825};
826
827#if OS_VXWORKS
828/*
drh9b35ea62008-11-29 02:20:26 +0000829** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000830** variable:
831*/
832static struct vxworksFileId *vxworksFileList = 0;
833
834/*
835** Simplify a filename into its canonical form
836** by making the following changes:
837**
838** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000839** * convert /./ into just /
840** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000841**
842** Changes are made in-place. Return the new name length.
843**
844** The original filename is in z[0..n-1]. Return the number of
845** characters in the simplified name.
846*/
847static int vxworksSimplifyName(char *z, int n){
848 int i, j;
849 while( n>1 && z[n-1]=='/' ){ n--; }
850 for(i=j=0; i<n; i++){
851 if( z[i]=='/' ){
852 if( z[i+1]=='/' ) continue;
853 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
854 i += 1;
855 continue;
856 }
857 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
858 while( j>0 && z[j-1]!='/' ){ j--; }
859 if( j>0 ){ j--; }
860 i += 2;
861 continue;
862 }
863 }
864 z[j++] = z[i];
865 }
866 z[j] = 0;
867 return j;
868}
869
870/*
871** Find a unique file ID for the given absolute pathname. Return
872** a pointer to the vxworksFileId object. This pointer is the unique
873** file ID.
874**
875** The nRef field of the vxworksFileId object is incremented before
876** the object is returned. A new vxworksFileId object is created
877** and added to the global list if necessary.
878**
879** If a memory allocation error occurs, return NULL.
880*/
881static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
882 struct vxworksFileId *pNew; /* search key and new file ID */
883 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
884 int n; /* Length of zAbsoluteName string */
885
886 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000887 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000888 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
889 if( pNew==0 ) return 0;
890 pNew->zCanonicalName = (char*)&pNew[1];
891 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
892 n = vxworksSimplifyName(pNew->zCanonicalName, n);
893
894 /* Search for an existing entry that matching the canonical name.
895 ** If found, increment the reference count and return a pointer to
896 ** the existing file ID.
897 */
898 unixEnterMutex();
899 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
900 if( pCandidate->nName==n
901 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
902 ){
903 sqlite3_free(pNew);
904 pCandidate->nRef++;
905 unixLeaveMutex();
906 return pCandidate;
907 }
908 }
909
910 /* No match was found. We will make a new file ID */
911 pNew->nRef = 1;
912 pNew->nName = n;
913 pNew->pNext = vxworksFileList;
914 vxworksFileList = pNew;
915 unixLeaveMutex();
916 return pNew;
917}
918
919/*
920** Decrement the reference count on a vxworksFileId object. Free
921** the object when the reference count reaches zero.
922*/
923static void vxworksReleaseFileId(struct vxworksFileId *pId){
924 unixEnterMutex();
925 assert( pId->nRef>0 );
926 pId->nRef--;
927 if( pId->nRef==0 ){
928 struct vxworksFileId **pp;
929 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
930 assert( *pp==pId );
931 *pp = pId->pNext;
932 sqlite3_free(pId);
933 }
934 unixLeaveMutex();
935}
936#endif /* OS_VXWORKS */
937/*************** End of Unique File ID Utility Used By VxWorks ****************
938******************************************************************************/
939
940
941/******************************************************************************
942*************************** Posix Advisory Locking ****************************
943**
drh9b35ea62008-11-29 02:20:26 +0000944** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000945** section 6.5.2.2 lines 483 through 490 specify that when a process
946** sets or clears a lock, that operation overrides any prior locks set
947** by the same process. It does not explicitly say so, but this implies
948** that it overrides locks set by the same process using a different
949** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000950**
951** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000952** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
953**
954** Suppose ./file1 and ./file2 are really the same file (because
955** one is a hard or symbolic link to the other) then if you set
956** an exclusive lock on fd1, then try to get an exclusive lock
957** on fd2, it works. I would have expected the second lock to
958** fail since there was already a lock on the file due to fd1.
959** But not so. Since both locks came from the same process, the
960** second overrides the first, even though they were on different
961** file descriptors opened on different file names.
962**
drh734c9862008-11-28 15:37:20 +0000963** This means that we cannot use POSIX locks to synchronize file access
964** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000965** to synchronize access for threads in separate processes, but not
966** threads within the same process.
967**
968** To work around the problem, SQLite has to manage file locks internally
969** on its own. Whenever a new database is opened, we have to find the
970** specific inode of the database file (the inode is determined by the
971** st_dev and st_ino fields of the stat structure that fstat() fills in)
972** and check for locks already existing on that inode. When locks are
973** created or removed, we have to look at our own internal record of the
974** locks to see if another thread has previously set a lock on that same
975** inode.
976**
drh9b35ea62008-11-29 02:20:26 +0000977** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
978** For VxWorks, we have to use the alternative unique ID system based on
979** canonical filename and implemented in the previous division.)
980**
danielk1977ad94b582007-08-20 06:44:22 +0000981** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000982** descriptor. It is now a structure that holds the integer file
983** descriptor and a pointer to a structure that describes the internal
984** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000985** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000986** point to the same locking structure. The locking structure keeps
987** a reference count (so we will know when to delete it) and a "cnt"
988** field that tells us its internal lock status. cnt==0 means the
989** file is unlocked. cnt==-1 means the file has an exclusive lock.
990** cnt>0 means there are cnt shared locks on the file.
991**
992** Any attempt to lock or unlock a file first checks the locking
993** structure. The fcntl() system call is only invoked to set a
994** POSIX lock if the internal lock structure transitions between
995** a locked and an unlocked state.
996**
drh734c9862008-11-28 15:37:20 +0000997** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000998**
999** If you close a file descriptor that points to a file that has locks,
1000** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001001** released. To work around this problem, each unixInodeInfo object
1002** maintains a count of the number of pending locks on tha inode.
1003** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001004** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001005** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001006** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001007** be closed and that list is walked (and cleared) when the last lock
1008** clears.
1009**
drh9b35ea62008-11-29 02:20:26 +00001010** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001011**
drh9b35ea62008-11-29 02:20:26 +00001012** Many older versions of linux use the LinuxThreads library which is
1013** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001014** A cannot be modified or overridden by a different thread B.
1015** Only thread A can modify the lock. Locking behavior is correct
1016** if the appliation uses the newer Native Posix Thread Library (NPTL)
1017** on linux - with NPTL a lock created by thread A can override locks
1018** in thread B. But there is no way to know at compile-time which
1019** threading library is being used. So there is no way to know at
1020** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001021** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001022** current process.
drh5fdae772004-06-29 03:29:00 +00001023**
drh8af6c222010-05-14 12:43:01 +00001024** SQLite used to support LinuxThreads. But support for LinuxThreads
1025** was dropped beginning with version 3.7.0. SQLite will still work with
1026** LinuxThreads provided that (1) there is no more than one connection
1027** per database file in the same process and (2) database connections
1028** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001029*/
1030
1031/*
1032** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001033** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001034*/
1035struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001036 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001037#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001038 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001039#else
drh107886a2008-11-21 22:21:50 +00001040 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001041#endif
1042};
1043
1044/*
drhbbd42a62004-05-22 17:41:58 +00001045** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001046** inode. Or, on LinuxThreads, there is one of these structures for
1047** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001048**
danielk1977ad94b582007-08-20 06:44:22 +00001049** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001050** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001051** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001052*/
drh8af6c222010-05-14 12:43:01 +00001053struct unixInodeInfo {
1054 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001055 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001056 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1057 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001058 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001059 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1060 int nLock; /* Number of outstanding file locks */
1061 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1062 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1063 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001064#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001065 unsigned long long sharedByte; /* for AFP simulated shared lock */
1066#endif
drh6c7d5c52008-11-21 20:32:33 +00001067#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001068 sem_t *pSem; /* Named POSIX semaphore */
1069 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001070#endif
drhbbd42a62004-05-22 17:41:58 +00001071};
1072
drhda0e7682008-07-30 15:27:54 +00001073/*
drh8af6c222010-05-14 12:43:01 +00001074** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001075*/
drhd91c68f2010-05-14 14:52:25 +00001076static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001077
drh5fdae772004-06-29 03:29:00 +00001078/*
dane18d4952011-02-21 11:46:24 +00001079**
1080** This function - unixLogError_x(), is only ever called via the macro
1081** unixLogError().
1082**
1083** It is invoked after an error occurs in an OS function and errno has been
1084** set. It logs a message using sqlite3_log() containing the current value of
1085** errno and, if possible, the human-readable equivalent from strerror() or
1086** strerror_r().
1087**
1088** The first argument passed to the macro should be the error code that
1089** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1090** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001091** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001092** if any.
1093*/
drh0e9365c2011-03-02 02:08:13 +00001094#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1095static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001096 int errcode, /* SQLite error code */
1097 const char *zFunc, /* Name of OS function that failed */
1098 const char *zPath, /* File path associated with error */
1099 int iLine /* Source line number where error occurred */
1100){
1101 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001102 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001103
1104 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1105 ** the strerror() function to obtain the human-readable error message
1106 ** equivalent to errno. Otherwise, use strerror_r().
1107 */
1108#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1109 char aErr[80];
1110 memset(aErr, 0, sizeof(aErr));
1111 zErr = aErr;
1112
1113 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001114 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001115 ** returns a pointer to a buffer containing the error message. That pointer
1116 ** may point to aErr[], or it may point to some static storage somewhere.
1117 ** Otherwise, assume that the system provides the POSIX version of
1118 ** strerror_r(), which always writes an error message into aErr[].
1119 **
1120 ** If the code incorrectly assumes that it is the POSIX version that is
1121 ** available, the error message will often be an empty string. Not a
1122 ** huge problem. Incorrectly concluding that the GNU version is available
1123 ** could lead to a segfault though.
1124 */
1125#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1126 zErr =
1127# endif
drh0e9365c2011-03-02 02:08:13 +00001128 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001129
1130#elif SQLITE_THREADSAFE
1131 /* This is a threadsafe build, but strerror_r() is not available. */
1132 zErr = "";
1133#else
1134 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001135 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001136#endif
1137
drh0e9365c2011-03-02 02:08:13 +00001138 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001139 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001140 "os_unix.c:%d: (%d) %s(%s) - %s",
1141 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001142 );
1143
1144 return errcode;
1145}
1146
drh0e9365c2011-03-02 02:08:13 +00001147/*
1148** Close a file descriptor.
1149**
1150** We assume that close() almost always works, since it is only in a
1151** very sick application or on a very sick platform that it might fail.
1152** If it does fail, simply leak the file descriptor, but do log the
1153** error.
1154**
1155** Note that it is not safe to retry close() after EINTR since the
1156** file descriptor might have already been reused by another thread.
1157** So we don't even try to recover from an EINTR. Just log the error
1158** and move on.
1159*/
1160static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001161 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001162 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1163 pFile ? pFile->zPath : 0, lineno);
1164 }
1165}
dane18d4952011-02-21 11:46:24 +00001166
1167/*
danb0ac3e32010-06-16 10:55:42 +00001168** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001169*/
drh0e9365c2011-03-02 02:08:13 +00001170static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001171 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001172 UnixUnusedFd *p;
1173 UnixUnusedFd *pNext;
1174 for(p=pInode->pUnused; p; p=pNext){
1175 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001176 robust_close(pFile, p->fd, __LINE__);
1177 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001178 }
drh0e9365c2011-03-02 02:08:13 +00001179 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001180}
1181
1182/*
drh8af6c222010-05-14 12:43:01 +00001183** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001184**
1185** The mutex entered using the unixEnterMutex() function must be held
1186** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001187*/
danb0ac3e32010-06-16 10:55:42 +00001188static void releaseInodeInfo(unixFile *pFile){
1189 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001190 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001191 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001192 pInode->nRef--;
1193 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001194 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001195 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001196 if( pInode->pPrev ){
1197 assert( pInode->pPrev->pNext==pInode );
1198 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001199 }else{
drh8af6c222010-05-14 12:43:01 +00001200 assert( inodeList==pInode );
1201 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001202 }
drh8af6c222010-05-14 12:43:01 +00001203 if( pInode->pNext ){
1204 assert( pInode->pNext->pPrev==pInode );
1205 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001206 }
drh8af6c222010-05-14 12:43:01 +00001207 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001208 }
drhbbd42a62004-05-22 17:41:58 +00001209 }
1210}
1211
1212/*
drh8af6c222010-05-14 12:43:01 +00001213** Given a file descriptor, locate the unixInodeInfo object that
1214** describes that file descriptor. Create a new one if necessary. The
1215** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001216**
dan9359c7b2009-08-21 08:29:10 +00001217** The mutex entered using the unixEnterMutex() function must be held
1218** when this function is called.
1219**
drh6c7d5c52008-11-21 20:32:33 +00001220** Return an appropriate error code.
1221*/
drh8af6c222010-05-14 12:43:01 +00001222static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001223 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001224 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001225){
1226 int rc; /* System call return code */
1227 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001228 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1229 struct stat statbuf; /* Low-level file information */
1230 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001231
dan9359c7b2009-08-21 08:29:10 +00001232 assert( unixMutexHeld() );
1233
drh6c7d5c52008-11-21 20:32:33 +00001234 /* Get low-level information about the file that we can used to
1235 ** create a unique name for the file.
1236 */
1237 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001238 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001239 if( rc!=0 ){
1240 pFile->lastErrno = errno;
1241#ifdef EOVERFLOW
1242 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1243#endif
1244 return SQLITE_IOERR;
1245 }
1246
drheb0d74f2009-02-03 15:27:02 +00001247#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001248 /* On OS X on an msdos filesystem, the inode number is reported
1249 ** incorrectly for zero-size files. See ticket #3260. To work
1250 ** around this problem (we consider it a bug in OS X, not SQLite)
1251 ** we always increase the file size to 1 by writing a single byte
1252 ** prior to accessing the inode number. The one byte written is
1253 ** an ASCII 'S' character which also happens to be the first byte
1254 ** in the header of every SQLite database. In this way, if there
1255 ** is a race condition such that another thread has already populated
1256 ** the first page of the database, no damage is done.
1257 */
drh7ed97b92010-01-20 13:07:21 +00001258 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001259 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001260 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001261 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001262 return SQLITE_IOERR;
1263 }
drh99ab3b12011-03-02 15:09:07 +00001264 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001265 if( rc!=0 ){
1266 pFile->lastErrno = errno;
1267 return SQLITE_IOERR;
1268 }
1269 }
drheb0d74f2009-02-03 15:27:02 +00001270#endif
drh6c7d5c52008-11-21 20:32:33 +00001271
drh8af6c222010-05-14 12:43:01 +00001272 memset(&fileId, 0, sizeof(fileId));
1273 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001274#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001275 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001276#else
drh8af6c222010-05-14 12:43:01 +00001277 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001278#endif
drh8af6c222010-05-14 12:43:01 +00001279 pInode = inodeList;
1280 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1281 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001282 }
drh8af6c222010-05-14 12:43:01 +00001283 if( pInode==0 ){
1284 pInode = sqlite3_malloc( sizeof(*pInode) );
1285 if( pInode==0 ){
1286 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001287 }
drh8af6c222010-05-14 12:43:01 +00001288 memset(pInode, 0, sizeof(*pInode));
1289 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1290 pInode->nRef = 1;
1291 pInode->pNext = inodeList;
1292 pInode->pPrev = 0;
1293 if( inodeList ) inodeList->pPrev = pInode;
1294 inodeList = pInode;
1295 }else{
1296 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001297 }
drh8af6c222010-05-14 12:43:01 +00001298 *ppInode = pInode;
1299 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001300}
drh6c7d5c52008-11-21 20:32:33 +00001301
aswift5b1a2562008-08-22 00:22:35 +00001302
1303/*
drhfbc7e882013-04-11 01:16:15 +00001304** Check a unixFile that is a database. Verify the following:
1305**
1306** (1) There is exactly one hard link on the file
1307** (2) The file is not a symbolic link
1308** (3) The file has not been renamed or unlinked
1309**
1310** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1311*/
1312static void verifyDbFile(unixFile *pFile){
1313 struct stat buf;
1314 int rc;
1315 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1316 /* One or more of the following warnings have already been issued. Do not
1317 ** repeat them so as not to clutter the error log */
1318 return;
1319 }
1320 rc = osFstat(pFile->h, &buf);
1321 if( rc!=0 ){
1322 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1323 pFile->ctrlFlags |= UNIXFILE_WARNED;
1324 return;
1325 }
1326 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
1327 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1328 pFile->ctrlFlags |= UNIXFILE_WARNED;
1329 return;
1330 }
1331 if( buf.st_nlink>1 ){
1332 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1333 pFile->ctrlFlags |= UNIXFILE_WARNED;
1334 return;
1335 }
1336 if( pFile->pInode!=0
1337 && ((rc = osStat(pFile->zPath, &buf))!=0
1338 || buf.st_ino!=pFile->pInode->fileId.ino)
1339 ){
1340 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1341 pFile->ctrlFlags |= UNIXFILE_WARNED;
1342 return;
1343 }
1344}
1345
1346
1347/*
danielk197713adf8a2004-06-03 16:08:41 +00001348** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001349** file by this or any other process. If such a lock is held, set *pResOut
1350** to a non-zero value otherwise *pResOut is set to zero. The return value
1351** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001352*/
danielk1977861f7452008-06-05 11:39:11 +00001353static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001354 int rc = SQLITE_OK;
1355 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001356 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001357
danielk1977861f7452008-06-05 11:39:11 +00001358 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1359
drh054889e2005-11-30 03:20:31 +00001360 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001361 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001362
1363 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001364 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001365 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001366 }
1367
drh2ac3ee92004-06-07 16:27:46 +00001368 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001369 */
danielk197709480a92009-02-09 05:32:32 +00001370#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001371 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001372 struct flock lock;
1373 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001374 lock.l_start = RESERVED_BYTE;
1375 lock.l_len = 1;
1376 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001377 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1378 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1379 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001380 } else if( lock.l_type!=F_UNLCK ){
1381 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001382 }
1383 }
danielk197709480a92009-02-09 05:32:32 +00001384#endif
danielk197713adf8a2004-06-03 16:08:41 +00001385
drh6c7d5c52008-11-21 20:32:33 +00001386 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001387 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001388
aswift5b1a2562008-08-22 00:22:35 +00001389 *pResOut = reserved;
1390 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001391}
1392
1393/*
drha7e61d82011-03-12 17:02:57 +00001394** Attempt to set a system-lock on the file pFile. The lock is
1395** described by pLock.
1396**
drh77197112011-03-15 19:08:48 +00001397** If the pFile was opened read/write from unix-excl, then the only lock
1398** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001399** the first time any lock is attempted. All subsequent system locking
1400** operations become no-ops. Locking operations still happen internally,
1401** in order to coordinate access between separate database connections
1402** within this process, but all of that is handled in memory and the
1403** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001404**
1405** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1406** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1407** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001408**
1409** Zero is returned if the call completes successfully, or -1 if a call
1410** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001411*/
1412static int unixFileLock(unixFile *pFile, struct flock *pLock){
1413 int rc;
drh3cb93392011-03-12 18:10:44 +00001414 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001415 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001416 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001417 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1418 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1419 ){
drh3cb93392011-03-12 18:10:44 +00001420 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001421 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001422 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001423 lock.l_whence = SEEK_SET;
1424 lock.l_start = SHARED_FIRST;
1425 lock.l_len = SHARED_SIZE;
1426 lock.l_type = F_WRLCK;
1427 rc = osFcntl(pFile->h, F_SETLK, &lock);
1428 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001429 pInode->bProcessLock = 1;
1430 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001431 }else{
1432 rc = 0;
1433 }
1434 }else{
1435 rc = osFcntl(pFile->h, F_SETLK, pLock);
1436 }
1437 return rc;
1438}
1439
1440/*
drh308c2a52010-05-14 11:30:18 +00001441** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001442** of the following:
1443**
drh2ac3ee92004-06-07 16:27:46 +00001444** (1) SHARED_LOCK
1445** (2) RESERVED_LOCK
1446** (3) PENDING_LOCK
1447** (4) EXCLUSIVE_LOCK
1448**
drhb3e04342004-06-08 00:47:47 +00001449** Sometimes when requesting one lock state, additional lock states
1450** are inserted in between. The locking might fail on one of the later
1451** transitions leaving the lock state different from what it started but
1452** still short of its goal. The following chart shows the allowed
1453** transitions and the inserted intermediate states:
1454**
1455** UNLOCKED -> SHARED
1456** SHARED -> RESERVED
1457** SHARED -> (PENDING) -> EXCLUSIVE
1458** RESERVED -> (PENDING) -> EXCLUSIVE
1459** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001460**
drha6abd042004-06-09 17:37:22 +00001461** This routine will only increase a lock. Use the sqlite3OsUnlock()
1462** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001463*/
drh308c2a52010-05-14 11:30:18 +00001464static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001465 /* The following describes the implementation of the various locks and
1466 ** lock transitions in terms of the POSIX advisory shared and exclusive
1467 ** lock primitives (called read-locks and write-locks below, to avoid
1468 ** confusion with SQLite lock names). The algorithms are complicated
1469 ** slightly in order to be compatible with windows systems simultaneously
1470 ** accessing the same database file, in case that is ever required.
1471 **
1472 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1473 ** byte', each single bytes at well known offsets, and the 'shared byte
1474 ** range', a range of 510 bytes at a well known offset.
1475 **
1476 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1477 ** byte'. If this is successful, a random byte from the 'shared byte
1478 ** range' is read-locked and the lock on the 'pending byte' released.
1479 **
danielk197790ba3bd2004-06-25 08:32:25 +00001480 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1481 ** A RESERVED lock is implemented by grabbing a write-lock on the
1482 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001483 **
1484 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001485 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1486 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1487 ** obtained, but existing SHARED locks are allowed to persist. A process
1488 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1489 ** This property is used by the algorithm for rolling back a journal file
1490 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001491 **
danielk197790ba3bd2004-06-25 08:32:25 +00001492 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1493 ** implemented by obtaining a write-lock on the entire 'shared byte
1494 ** range'. Since all other locks require a read-lock on one of the bytes
1495 ** within this range, this ensures that no other locks are held on the
1496 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001497 **
1498 ** The reason a single byte cannot be used instead of the 'shared byte
1499 ** range' is that some versions of windows do not support read-locks. By
1500 ** locking a random byte from a range, concurrent SHARED locks may exist
1501 ** even if the locking primitive used is always a write-lock.
1502 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001503 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001504 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001505 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001506 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001507 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001508
drh054889e2005-11-30 03:20:31 +00001509 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001510 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1511 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001512 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001513
1514 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001515 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001516 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001517 */
drh308c2a52010-05-14 11:30:18 +00001518 if( pFile->eFileLock>=eFileLock ){
1519 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1520 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001521 return SQLITE_OK;
1522 }
1523
drh0c2694b2009-09-03 16:23:44 +00001524 /* Make sure the locking sequence is correct.
1525 ** (1) We never move from unlocked to anything higher than shared lock.
1526 ** (2) SQLite never explicitly requests a pendig lock.
1527 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001528 */
drh308c2a52010-05-14 11:30:18 +00001529 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1530 assert( eFileLock!=PENDING_LOCK );
1531 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001532
drh8af6c222010-05-14 12:43:01 +00001533 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001534 */
drh6c7d5c52008-11-21 20:32:33 +00001535 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001536 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001537
danielk1977ad94b582007-08-20 06:44:22 +00001538 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001539 ** handle that precludes the requested lock, return BUSY.
1540 */
drh8af6c222010-05-14 12:43:01 +00001541 if( (pFile->eFileLock!=pInode->eFileLock &&
1542 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001543 ){
1544 rc = SQLITE_BUSY;
1545 goto end_lock;
1546 }
1547
1548 /* If a SHARED lock is requested, and some thread using this PID already
1549 ** has a SHARED or RESERVED lock, then increment reference counts and
1550 ** return SQLITE_OK.
1551 */
drh308c2a52010-05-14 11:30:18 +00001552 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001553 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001554 assert( eFileLock==SHARED_LOCK );
1555 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001556 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001557 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001558 pInode->nShared++;
1559 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001560 goto end_lock;
1561 }
1562
danielk19779a1d0ab2004-06-01 14:09:28 +00001563
drh3cde3bb2004-06-12 02:17:14 +00001564 /* A PENDING lock is needed before acquiring a SHARED lock and before
1565 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1566 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001567 */
drh0c2694b2009-09-03 16:23:44 +00001568 lock.l_len = 1L;
1569 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001570 if( eFileLock==SHARED_LOCK
1571 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001572 ){
drh308c2a52010-05-14 11:30:18 +00001573 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001574 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001575 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001576 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001577 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001578 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001579 pFile->lastErrno = tErrno;
1580 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001581 goto end_lock;
1582 }
drh3cde3bb2004-06-12 02:17:14 +00001583 }
1584
1585
1586 /* If control gets to this point, then actually go ahead and make
1587 ** operating system calls for the specified lock.
1588 */
drh308c2a52010-05-14 11:30:18 +00001589 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001590 assert( pInode->nShared==0 );
1591 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001592 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001593
drh2ac3ee92004-06-07 16:27:46 +00001594 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001595 lock.l_start = SHARED_FIRST;
1596 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001597 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001598 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001599 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001600 }
dan661d71a2011-03-30 19:08:03 +00001601
drh2ac3ee92004-06-07 16:27:46 +00001602 /* Drop the temporary PENDING lock */
1603 lock.l_start = PENDING_BYTE;
1604 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001605 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001606 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1607 /* This could happen with a network mount */
1608 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001609 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001610 }
dan661d71a2011-03-30 19:08:03 +00001611
1612 if( rc ){
1613 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001614 pFile->lastErrno = tErrno;
1615 }
dan661d71a2011-03-30 19:08:03 +00001616 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001617 }else{
drh308c2a52010-05-14 11:30:18 +00001618 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001619 pInode->nLock++;
1620 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001621 }
drh8af6c222010-05-14 12:43:01 +00001622 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001623 /* We are trying for an exclusive lock but another thread in this
1624 ** same process is still holding a shared lock. */
1625 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001626 }else{
drh3cde3bb2004-06-12 02:17:14 +00001627 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001628 ** assumed that there is a SHARED or greater lock on the file
1629 ** already.
1630 */
drh308c2a52010-05-14 11:30:18 +00001631 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001632 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001633
1634 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1635 if( eFileLock==RESERVED_LOCK ){
1636 lock.l_start = RESERVED_BYTE;
1637 lock.l_len = 1L;
1638 }else{
1639 lock.l_start = SHARED_FIRST;
1640 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001641 }
dan661d71a2011-03-30 19:08:03 +00001642
1643 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001644 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001645 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001646 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001647 pFile->lastErrno = tErrno;
1648 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001649 }
drhbbd42a62004-05-22 17:41:58 +00001650 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001651
drh8f941bc2009-01-14 23:03:40 +00001652
drhd3d8c042012-05-29 17:02:40 +00001653#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001654 /* Set up the transaction-counter change checking flags when
1655 ** transitioning from a SHARED to a RESERVED lock. The change
1656 ** from SHARED to RESERVED marks the beginning of a normal
1657 ** write operation (not a hot journal rollback).
1658 */
1659 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001660 && pFile->eFileLock<=SHARED_LOCK
1661 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001662 ){
1663 pFile->transCntrChng = 0;
1664 pFile->dbUpdate = 0;
1665 pFile->inNormalWrite = 1;
1666 }
1667#endif
1668
1669
danielk1977ecb2a962004-06-02 06:30:16 +00001670 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001671 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001672 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001673 }else if( eFileLock==EXCLUSIVE_LOCK ){
1674 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001675 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001676 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001677
1678end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001679 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001680 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1681 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001682 return rc;
1683}
1684
1685/*
dan08da86a2009-08-21 17:18:03 +00001686** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001687** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001688*/
1689static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001690 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001691 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001692 p->pNext = pInode->pUnused;
1693 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001694 pFile->h = -1;
1695 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001696}
1697
1698/*
drh308c2a52010-05-14 11:30:18 +00001699** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001700** must be either NO_LOCK or SHARED_LOCK.
1701**
1702** If the locking level of the file descriptor is already at or below
1703** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001704**
1705** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1706** the byte range is divided into 2 parts and the first part is unlocked then
1707** set to a read lock, then the other part is simply unlocked. This works
1708** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1709** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001710*/
drha7e61d82011-03-12 17:02:57 +00001711static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001712 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001713 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001714 struct flock lock;
1715 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001716
drh054889e2005-11-30 03:20:31 +00001717 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001718 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001719 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001720 getpid()));
drha6abd042004-06-09 17:37:22 +00001721
drh308c2a52010-05-14 11:30:18 +00001722 assert( eFileLock<=SHARED_LOCK );
1723 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001724 return SQLITE_OK;
1725 }
drh6c7d5c52008-11-21 20:32:33 +00001726 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001727 pInode = pFile->pInode;
1728 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001729 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001730 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001731
drhd3d8c042012-05-29 17:02:40 +00001732#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001733 /* When reducing a lock such that other processes can start
1734 ** reading the database file again, make sure that the
1735 ** transaction counter was updated if any part of the database
1736 ** file changed. If the transaction counter is not updated,
1737 ** other connections to the same file might not realize that
1738 ** the file has changed and hence might not know to flush their
1739 ** cache. The use of a stale cache can lead to database corruption.
1740 */
drh8f941bc2009-01-14 23:03:40 +00001741 pFile->inNormalWrite = 0;
1742#endif
1743
drh7ed97b92010-01-20 13:07:21 +00001744 /* downgrading to a shared lock on NFS involves clearing the write lock
1745 ** before establishing the readlock - to avoid a race condition we downgrade
1746 ** the lock in 2 blocks, so that part of the range will be covered by a
1747 ** write lock until the rest is covered by a read lock:
1748 ** 1: [WWWWW]
1749 ** 2: [....W]
1750 ** 3: [RRRRW]
1751 ** 4: [RRRR.]
1752 */
drh308c2a52010-05-14 11:30:18 +00001753 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001754
1755#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001756 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001757 assert( handleNFSUnlock==0 );
1758#endif
1759#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001760 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001761 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001762 off_t divSize = SHARED_SIZE - 1;
1763
1764 lock.l_type = F_UNLCK;
1765 lock.l_whence = SEEK_SET;
1766 lock.l_start = SHARED_FIRST;
1767 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001768 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001769 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001770 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001771 if( IS_LOCK_ERROR(rc) ){
1772 pFile->lastErrno = tErrno;
1773 }
1774 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001775 }
drh7ed97b92010-01-20 13:07:21 +00001776 lock.l_type = F_RDLCK;
1777 lock.l_whence = SEEK_SET;
1778 lock.l_start = SHARED_FIRST;
1779 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001780 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001781 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001782 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1783 if( IS_LOCK_ERROR(rc) ){
1784 pFile->lastErrno = tErrno;
1785 }
1786 goto end_unlock;
1787 }
1788 lock.l_type = F_UNLCK;
1789 lock.l_whence = SEEK_SET;
1790 lock.l_start = SHARED_FIRST+divSize;
1791 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001792 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001793 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001794 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001795 if( IS_LOCK_ERROR(rc) ){
1796 pFile->lastErrno = tErrno;
1797 }
1798 goto end_unlock;
1799 }
drh30f776f2011-02-25 03:25:07 +00001800 }else
1801#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1802 {
drh7ed97b92010-01-20 13:07:21 +00001803 lock.l_type = F_RDLCK;
1804 lock.l_whence = SEEK_SET;
1805 lock.l_start = SHARED_FIRST;
1806 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001807 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001808 /* In theory, the call to unixFileLock() cannot fail because another
1809 ** process is holding an incompatible lock. If it does, this
1810 ** indicates that the other process is not following the locking
1811 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1812 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1813 ** an assert to fail). */
1814 rc = SQLITE_IOERR_RDLOCK;
1815 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001816 goto end_unlock;
1817 }
drh9c105bb2004-10-02 20:38:28 +00001818 }
1819 }
drhbbd42a62004-05-22 17:41:58 +00001820 lock.l_type = F_UNLCK;
1821 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001822 lock.l_start = PENDING_BYTE;
1823 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001824 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001825 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001826 }else{
danea83bc62011-04-01 11:56:32 +00001827 rc = SQLITE_IOERR_UNLOCK;
1828 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001829 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001830 }
drhbbd42a62004-05-22 17:41:58 +00001831 }
drh308c2a52010-05-14 11:30:18 +00001832 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001833 /* Decrement the shared lock counter. Release the lock using an
1834 ** OS call only when all threads in this same process have released
1835 ** the lock.
1836 */
drh8af6c222010-05-14 12:43:01 +00001837 pInode->nShared--;
1838 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001839 lock.l_type = F_UNLCK;
1840 lock.l_whence = SEEK_SET;
1841 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001842 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001843 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001844 }else{
danea83bc62011-04-01 11:56:32 +00001845 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001846 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001847 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001848 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001849 }
drha6abd042004-06-09 17:37:22 +00001850 }
1851
drhbbd42a62004-05-22 17:41:58 +00001852 /* Decrement the count of locks against this same file. When the
1853 ** count reaches zero, close any other file descriptors whose close
1854 ** was deferred because of outstanding locks.
1855 */
drh8af6c222010-05-14 12:43:01 +00001856 pInode->nLock--;
1857 assert( pInode->nLock>=0 );
1858 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001859 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001860 }
1861 }
drhf2f105d2012-08-20 15:53:54 +00001862
aswift5b1a2562008-08-22 00:22:35 +00001863end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001864 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001865 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001866 return rc;
drhbbd42a62004-05-22 17:41:58 +00001867}
1868
1869/*
drh308c2a52010-05-14 11:30:18 +00001870** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001871** must be either NO_LOCK or SHARED_LOCK.
1872**
1873** If the locking level of the file descriptor is already at or below
1874** the requested locking level, this routine is a no-op.
1875*/
drh308c2a52010-05-14 11:30:18 +00001876static int unixUnlock(sqlite3_file *id, int eFileLock){
dana1afc742013-03-25 13:50:49 +00001877 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
drha7e61d82011-03-12 17:02:57 +00001878 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001879}
1880
danf23da962013-03-23 21:00:41 +00001881static int unixMapfile(unixFile *pFd, i64 nByte);
1882static void unixUnmapfile(unixFile *pFd);
1883
drh7ed97b92010-01-20 13:07:21 +00001884/*
danielk1977e339d652008-06-28 11:23:00 +00001885** This function performs the parts of the "close file" operation
1886** common to all locking schemes. It closes the directory and file
1887** handles, if they are valid, and sets all fields of the unixFile
1888** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001889**
1890** It is *not* necessary to hold the mutex when this routine is called,
1891** even on VxWorks. A mutex will be acquired on VxWorks by the
1892** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001893*/
1894static int closeUnixFile(sqlite3_file *id){
1895 unixFile *pFile = (unixFile*)id;
danf23da962013-03-23 21:00:41 +00001896 unixUnmapfile(pFile);
dan661d71a2011-03-30 19:08:03 +00001897 if( pFile->h>=0 ){
1898 robust_close(pFile, pFile->h, __LINE__);
1899 pFile->h = -1;
1900 }
1901#if OS_VXWORKS
1902 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001903 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001904 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001905 }
1906 vxworksReleaseFileId(pFile->pId);
1907 pFile->pId = 0;
1908 }
1909#endif
1910 OSTRACE(("CLOSE %-3d\n", pFile->h));
1911 OpenCounter(-1);
1912 sqlite3_free(pFile->pUnused);
1913 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001914 return SQLITE_OK;
1915}
1916
1917/*
danielk1977e3026632004-06-22 11:29:02 +00001918** Close a file.
1919*/
danielk197762079062007-08-15 17:08:46 +00001920static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001921 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001922 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001923 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001924 unixUnlock(id, NO_LOCK);
1925 unixEnterMutex();
1926
1927 /* unixFile.pInode is always valid here. Otherwise, a different close
1928 ** routine (e.g. nolockClose()) would be called instead.
1929 */
1930 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1931 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1932 /* If there are outstanding locks, do not actually close the file just
1933 ** yet because that would clear those locks. Instead, add the file
1934 ** descriptor to pInode->pUnused list. It will be automatically closed
1935 ** when the last lock is cleared.
1936 */
1937 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001938 }
dan661d71a2011-03-30 19:08:03 +00001939 releaseInodeInfo(pFile);
1940 rc = closeUnixFile(id);
1941 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001942 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001943}
1944
drh734c9862008-11-28 15:37:20 +00001945/************** End of the posix advisory lock implementation *****************
1946******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001947
drh734c9862008-11-28 15:37:20 +00001948/******************************************************************************
1949****************************** No-op Locking **********************************
1950**
1951** Of the various locking implementations available, this is by far the
1952** simplest: locking is ignored. No attempt is made to lock the database
1953** file for reading or writing.
1954**
1955** This locking mode is appropriate for use on read-only databases
1956** (ex: databases that are burned into CD-ROM, for example.) It can
1957** also be used if the application employs some external mechanism to
1958** prevent simultaneous access of the same database by two or more
1959** database connections. But there is a serious risk of database
1960** corruption if this locking mode is used in situations where multiple
1961** database connections are accessing the same database file at the same
1962** time and one or more of those connections are writing.
1963*/
drhbfe66312006-10-03 17:40:40 +00001964
drh734c9862008-11-28 15:37:20 +00001965static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1966 UNUSED_PARAMETER(NotUsed);
1967 *pResOut = 0;
1968 return SQLITE_OK;
1969}
drh734c9862008-11-28 15:37:20 +00001970static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1971 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1972 return SQLITE_OK;
1973}
drh734c9862008-11-28 15:37:20 +00001974static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1975 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1976 return SQLITE_OK;
1977}
1978
1979/*
drh9b35ea62008-11-29 02:20:26 +00001980** Close the file.
drh734c9862008-11-28 15:37:20 +00001981*/
1982static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001983 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001984}
1985
1986/******************* End of the no-op lock implementation *********************
1987******************************************************************************/
1988
1989/******************************************************************************
1990************************* Begin dot-file Locking ******************************
1991**
mistachkin48864df2013-03-21 21:20:32 +00001992** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001993** files (really a directory) to control access to the database. This works
1994** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001995**
1996** (1) There is zero concurrency. A single reader blocks all other
1997** connections from reading or writing the database.
1998**
1999** (2) An application crash or power loss can leave stale lock files
2000** sitting around that need to be cleared manually.
2001**
2002** Nevertheless, a dotlock is an appropriate locking mode for use if no
2003** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002004**
drh9ef6bc42011-11-04 02:24:02 +00002005** Dotfile locking works by creating a subdirectory in the same directory as
2006** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002007** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002008** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002009*/
2010
2011/*
2012** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002013** lock directory.
drh734c9862008-11-28 15:37:20 +00002014*/
2015#define DOTLOCK_SUFFIX ".lock"
2016
drh7708e972008-11-29 00:56:52 +00002017/*
2018** This routine checks if there is a RESERVED lock held on the specified
2019** file by this or any other process. If such a lock is held, set *pResOut
2020** to a non-zero value otherwise *pResOut is set to zero. The return value
2021** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2022**
2023** In dotfile locking, either a lock exists or it does not. So in this
2024** variation of CheckReservedLock(), *pResOut is set to true if any lock
2025** is held on the file and false if the file is unlocked.
2026*/
drh734c9862008-11-28 15:37:20 +00002027static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2028 int rc = SQLITE_OK;
2029 int reserved = 0;
2030 unixFile *pFile = (unixFile*)id;
2031
2032 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2033
2034 assert( pFile );
2035
2036 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002037 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002038 /* Either this connection or some other connection in the same process
2039 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002040 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002041 }else{
2042 /* The lock is held if and only if the lockfile exists */
2043 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002044 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002045 }
drh308c2a52010-05-14 11:30:18 +00002046 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002047 *pResOut = reserved;
2048 return rc;
2049}
2050
drh7708e972008-11-29 00:56:52 +00002051/*
drh308c2a52010-05-14 11:30:18 +00002052** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002053** of the following:
2054**
2055** (1) SHARED_LOCK
2056** (2) RESERVED_LOCK
2057** (3) PENDING_LOCK
2058** (4) EXCLUSIVE_LOCK
2059**
2060** Sometimes when requesting one lock state, additional lock states
2061** are inserted in between. The locking might fail on one of the later
2062** transitions leaving the lock state different from what it started but
2063** still short of its goal. The following chart shows the allowed
2064** transitions and the inserted intermediate states:
2065**
2066** UNLOCKED -> SHARED
2067** SHARED -> RESERVED
2068** SHARED -> (PENDING) -> EXCLUSIVE
2069** RESERVED -> (PENDING) -> EXCLUSIVE
2070** PENDING -> EXCLUSIVE
2071**
2072** This routine will only increase a lock. Use the sqlite3OsUnlock()
2073** routine to lower a locking level.
2074**
2075** With dotfile locking, we really only support state (4): EXCLUSIVE.
2076** But we track the other locking levels internally.
2077*/
drh308c2a52010-05-14 11:30:18 +00002078static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002079 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002080 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002081 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002082
drh7708e972008-11-29 00:56:52 +00002083
2084 /* If we have any lock, then the lock file already exists. All we have
2085 ** to do is adjust our internal record of the lock level.
2086 */
drh308c2a52010-05-14 11:30:18 +00002087 if( pFile->eFileLock > NO_LOCK ){
2088 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002089 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002090#ifdef HAVE_UTIME
2091 utime(zLockFile, NULL);
2092#else
drh734c9862008-11-28 15:37:20 +00002093 utimes(zLockFile, NULL);
2094#endif
drh7708e972008-11-29 00:56:52 +00002095 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002096 }
2097
2098 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002099 rc = osMkdir(zLockFile, 0777);
2100 if( rc<0 ){
2101 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002102 int tErrno = errno;
2103 if( EEXIST == tErrno ){
2104 rc = SQLITE_BUSY;
2105 } else {
2106 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2107 if( IS_LOCK_ERROR(rc) ){
2108 pFile->lastErrno = tErrno;
2109 }
2110 }
drh7708e972008-11-29 00:56:52 +00002111 return rc;
drh734c9862008-11-28 15:37:20 +00002112 }
drh734c9862008-11-28 15:37:20 +00002113
2114 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002115 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002116 return rc;
2117}
2118
drh7708e972008-11-29 00:56:52 +00002119/*
drh308c2a52010-05-14 11:30:18 +00002120** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002121** must be either NO_LOCK or SHARED_LOCK.
2122**
2123** If the locking level of the file descriptor is already at or below
2124** the requested locking level, this routine is a no-op.
2125**
2126** When the locking level reaches NO_LOCK, delete the lock file.
2127*/
drh308c2a52010-05-14 11:30:18 +00002128static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002129 unixFile *pFile = (unixFile*)id;
2130 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002131 int rc;
drh734c9862008-11-28 15:37:20 +00002132
2133 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002134 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002135 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002136 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002137
2138 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002139 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002140 return SQLITE_OK;
2141 }
drh7708e972008-11-29 00:56:52 +00002142
2143 /* To downgrade to shared, simply update our internal notion of the
2144 ** lock state. No need to mess with the file on disk.
2145 */
drh308c2a52010-05-14 11:30:18 +00002146 if( eFileLock==SHARED_LOCK ){
2147 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002148 return SQLITE_OK;
2149 }
2150
drh7708e972008-11-29 00:56:52 +00002151 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002152 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002153 rc = osRmdir(zLockFile);
2154 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2155 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002156 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002157 rc = 0;
drh734c9862008-11-28 15:37:20 +00002158 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002159 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002160 }
2161 if( IS_LOCK_ERROR(rc) ){
2162 pFile->lastErrno = tErrno;
2163 }
2164 return rc;
2165 }
drh308c2a52010-05-14 11:30:18 +00002166 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002167 return SQLITE_OK;
2168}
2169
2170/*
drh9b35ea62008-11-29 02:20:26 +00002171** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002172*/
2173static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002174 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002175 if( id ){
2176 unixFile *pFile = (unixFile*)id;
2177 dotlockUnlock(id, NO_LOCK);
2178 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002179 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002180 }
drh734c9862008-11-28 15:37:20 +00002181 return rc;
2182}
2183/****************** End of the dot-file lock implementation *******************
2184******************************************************************************/
2185
2186/******************************************************************************
2187************************** Begin flock Locking ********************************
2188**
2189** Use the flock() system call to do file locking.
2190**
drh6b9d6dd2008-12-03 19:34:47 +00002191** flock() locking is like dot-file locking in that the various
2192** fine-grain locking levels supported by SQLite are collapsed into
2193** a single exclusive lock. In other words, SHARED, RESERVED, and
2194** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2195** still works when you do this, but concurrency is reduced since
2196** only a single process can be reading the database at a time.
2197**
drh734c9862008-11-28 15:37:20 +00002198** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2199** compiling for VXWORKS.
2200*/
2201#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002202
drh6b9d6dd2008-12-03 19:34:47 +00002203/*
drhff812312011-02-23 13:33:46 +00002204** Retry flock() calls that fail with EINTR
2205*/
2206#ifdef EINTR
2207static int robust_flock(int fd, int op){
2208 int rc;
2209 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2210 return rc;
2211}
2212#else
drh5c819272011-02-23 14:00:12 +00002213# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002214#endif
2215
2216
2217/*
drh6b9d6dd2008-12-03 19:34:47 +00002218** This routine checks if there is a RESERVED lock held on the specified
2219** file by this or any other process. If such a lock is held, set *pResOut
2220** to a non-zero value otherwise *pResOut is set to zero. The return value
2221** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2222*/
drh734c9862008-11-28 15:37:20 +00002223static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2224 int rc = SQLITE_OK;
2225 int reserved = 0;
2226 unixFile *pFile = (unixFile*)id;
2227
2228 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2229
2230 assert( pFile );
2231
2232 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002233 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002234 reserved = 1;
2235 }
2236
2237 /* Otherwise see if some other process holds it. */
2238 if( !reserved ){
2239 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002240 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002241 if( !lrc ){
2242 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002243 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002244 if ( lrc ) {
2245 int tErrno = errno;
2246 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002247 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002248 if( IS_LOCK_ERROR(lrc) ){
2249 pFile->lastErrno = tErrno;
2250 rc = lrc;
2251 }
2252 }
2253 } else {
2254 int tErrno = errno;
2255 reserved = 1;
2256 /* someone else might have it reserved */
2257 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2258 if( IS_LOCK_ERROR(lrc) ){
2259 pFile->lastErrno = tErrno;
2260 rc = lrc;
2261 }
2262 }
2263 }
drh308c2a52010-05-14 11:30:18 +00002264 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002265
2266#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2267 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2268 rc = SQLITE_OK;
2269 reserved=1;
2270 }
2271#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2272 *pResOut = reserved;
2273 return rc;
2274}
2275
drh6b9d6dd2008-12-03 19:34:47 +00002276/*
drh308c2a52010-05-14 11:30:18 +00002277** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002278** of the following:
2279**
2280** (1) SHARED_LOCK
2281** (2) RESERVED_LOCK
2282** (3) PENDING_LOCK
2283** (4) EXCLUSIVE_LOCK
2284**
2285** Sometimes when requesting one lock state, additional lock states
2286** are inserted in between. The locking might fail on one of the later
2287** transitions leaving the lock state different from what it started but
2288** still short of its goal. The following chart shows the allowed
2289** transitions and the inserted intermediate states:
2290**
2291** UNLOCKED -> SHARED
2292** SHARED -> RESERVED
2293** SHARED -> (PENDING) -> EXCLUSIVE
2294** RESERVED -> (PENDING) -> EXCLUSIVE
2295** PENDING -> EXCLUSIVE
2296**
2297** flock() only really support EXCLUSIVE locks. We track intermediate
2298** lock states in the sqlite3_file structure, but all locks SHARED or
2299** above are really EXCLUSIVE locks and exclude all other processes from
2300** access the file.
2301**
2302** This routine will only increase a lock. Use the sqlite3OsUnlock()
2303** routine to lower a locking level.
2304*/
drh308c2a52010-05-14 11:30:18 +00002305static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002306 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002307 unixFile *pFile = (unixFile*)id;
2308
2309 assert( pFile );
2310
2311 /* if we already have a lock, it is exclusive.
2312 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002313 if (pFile->eFileLock > NO_LOCK) {
2314 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002315 return SQLITE_OK;
2316 }
2317
2318 /* grab an exclusive lock */
2319
drhff812312011-02-23 13:33:46 +00002320 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002321 int tErrno = errno;
2322 /* didn't get, must be busy */
2323 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2324 if( IS_LOCK_ERROR(rc) ){
2325 pFile->lastErrno = tErrno;
2326 }
2327 } else {
2328 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002329 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002330 }
drh308c2a52010-05-14 11:30:18 +00002331 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2332 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002333#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2334 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2335 rc = SQLITE_BUSY;
2336 }
2337#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2338 return rc;
2339}
2340
drh6b9d6dd2008-12-03 19:34:47 +00002341
2342/*
drh308c2a52010-05-14 11:30:18 +00002343** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002344** must be either NO_LOCK or SHARED_LOCK.
2345**
2346** If the locking level of the file descriptor is already at or below
2347** the requested locking level, this routine is a no-op.
2348*/
drh308c2a52010-05-14 11:30:18 +00002349static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002350 unixFile *pFile = (unixFile*)id;
2351
2352 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002353 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2354 pFile->eFileLock, getpid()));
2355 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002356
2357 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002358 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002359 return SQLITE_OK;
2360 }
2361
2362 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002363 if (eFileLock==SHARED_LOCK) {
2364 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002365 return SQLITE_OK;
2366 }
2367
2368 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002369 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002370#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002371 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002372#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002373 return SQLITE_IOERR_UNLOCK;
2374 }else{
drh308c2a52010-05-14 11:30:18 +00002375 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002376 return SQLITE_OK;
2377 }
2378}
2379
2380/*
2381** Close a file.
2382*/
2383static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002384 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002385 if( id ){
2386 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002387 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002388 }
drh5a05be12012-10-09 18:51:44 +00002389 return rc;
drh734c9862008-11-28 15:37:20 +00002390}
2391
2392#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2393
2394/******************* End of the flock lock implementation *********************
2395******************************************************************************/
2396
2397/******************************************************************************
2398************************ Begin Named Semaphore Locking ************************
2399**
2400** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002401**
2402** Semaphore locking is like dot-lock and flock in that it really only
2403** supports EXCLUSIVE locking. Only a single process can read or write
2404** the database file at a time. This reduces potential concurrency, but
2405** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002406*/
2407#if OS_VXWORKS
2408
drh6b9d6dd2008-12-03 19:34:47 +00002409/*
2410** This routine checks if there is a RESERVED lock held on the specified
2411** file by this or any other process. If such a lock is held, set *pResOut
2412** to a non-zero value otherwise *pResOut is set to zero. The return value
2413** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2414*/
drh734c9862008-11-28 15:37:20 +00002415static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2416 int rc = SQLITE_OK;
2417 int reserved = 0;
2418 unixFile *pFile = (unixFile*)id;
2419
2420 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2421
2422 assert( pFile );
2423
2424 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002425 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002426 reserved = 1;
2427 }
2428
2429 /* Otherwise see if some other process holds it. */
2430 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002431 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002432 struct stat statBuf;
2433
2434 if( sem_trywait(pSem)==-1 ){
2435 int tErrno = errno;
2436 if( EAGAIN != tErrno ){
2437 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2438 pFile->lastErrno = tErrno;
2439 } else {
2440 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002441 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002442 }
2443 }else{
2444 /* we could have it if we want it */
2445 sem_post(pSem);
2446 }
2447 }
drh308c2a52010-05-14 11:30:18 +00002448 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002449
2450 *pResOut = reserved;
2451 return rc;
2452}
2453
drh6b9d6dd2008-12-03 19:34:47 +00002454/*
drh308c2a52010-05-14 11:30:18 +00002455** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002456** of the following:
2457**
2458** (1) SHARED_LOCK
2459** (2) RESERVED_LOCK
2460** (3) PENDING_LOCK
2461** (4) EXCLUSIVE_LOCK
2462**
2463** Sometimes when requesting one lock state, additional lock states
2464** are inserted in between. The locking might fail on one of the later
2465** transitions leaving the lock state different from what it started but
2466** still short of its goal. The following chart shows the allowed
2467** transitions and the inserted intermediate states:
2468**
2469** UNLOCKED -> SHARED
2470** SHARED -> RESERVED
2471** SHARED -> (PENDING) -> EXCLUSIVE
2472** RESERVED -> (PENDING) -> EXCLUSIVE
2473** PENDING -> EXCLUSIVE
2474**
2475** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2476** lock states in the sqlite3_file structure, but all locks SHARED or
2477** above are really EXCLUSIVE locks and exclude all other processes from
2478** access the file.
2479**
2480** This routine will only increase a lock. Use the sqlite3OsUnlock()
2481** routine to lower a locking level.
2482*/
drh308c2a52010-05-14 11:30:18 +00002483static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002484 unixFile *pFile = (unixFile*)id;
2485 int fd;
drh8af6c222010-05-14 12:43:01 +00002486 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002487 int rc = SQLITE_OK;
2488
2489 /* if we already have a lock, it is exclusive.
2490 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002491 if (pFile->eFileLock > NO_LOCK) {
2492 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002493 rc = SQLITE_OK;
2494 goto sem_end_lock;
2495 }
2496
2497 /* lock semaphore now but bail out when already locked. */
2498 if( sem_trywait(pSem)==-1 ){
2499 rc = SQLITE_BUSY;
2500 goto sem_end_lock;
2501 }
2502
2503 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002504 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002505
2506 sem_end_lock:
2507 return rc;
2508}
2509
drh6b9d6dd2008-12-03 19:34:47 +00002510/*
drh308c2a52010-05-14 11:30:18 +00002511** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002512** must be either NO_LOCK or SHARED_LOCK.
2513**
2514** If the locking level of the file descriptor is already at or below
2515** the requested locking level, this routine is a no-op.
2516*/
drh308c2a52010-05-14 11:30:18 +00002517static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002518 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002519 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002520
2521 assert( pFile );
2522 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002523 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002524 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002525 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002526
2527 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002528 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002529 return SQLITE_OK;
2530 }
2531
2532 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002533 if (eFileLock==SHARED_LOCK) {
2534 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002535 return SQLITE_OK;
2536 }
2537
2538 /* no, really unlock. */
2539 if ( sem_post(pSem)==-1 ) {
2540 int rc, tErrno = errno;
2541 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2542 if( IS_LOCK_ERROR(rc) ){
2543 pFile->lastErrno = tErrno;
2544 }
2545 return rc;
2546 }
drh308c2a52010-05-14 11:30:18 +00002547 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002548 return SQLITE_OK;
2549}
2550
2551/*
2552 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002553 */
drh734c9862008-11-28 15:37:20 +00002554static int semClose(sqlite3_file *id) {
2555 if( id ){
2556 unixFile *pFile = (unixFile*)id;
2557 semUnlock(id, NO_LOCK);
2558 assert( pFile );
2559 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002560 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002561 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002562 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002563 }
2564 return SQLITE_OK;
2565}
2566
2567#endif /* OS_VXWORKS */
2568/*
2569** Named semaphore locking is only available on VxWorks.
2570**
2571*************** End of the named semaphore lock implementation ****************
2572******************************************************************************/
2573
2574
2575/******************************************************************************
2576*************************** Begin AFP Locking *********************************
2577**
2578** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2579** on Apple Macintosh computers - both OS9 and OSX.
2580**
2581** Third-party implementations of AFP are available. But this code here
2582** only works on OSX.
2583*/
2584
drhd2cb50b2009-01-09 21:41:17 +00002585#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002586/*
2587** The afpLockingContext structure contains all afp lock specific state
2588*/
drhbfe66312006-10-03 17:40:40 +00002589typedef struct afpLockingContext afpLockingContext;
2590struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002591 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002592 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002593};
2594
2595struct ByteRangeLockPB2
2596{
2597 unsigned long long offset; /* offset to first byte to lock */
2598 unsigned long long length; /* nbr of bytes to lock */
2599 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2600 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2601 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2602 int fd; /* file desc to assoc this lock with */
2603};
2604
drhfd131da2007-08-07 17:13:03 +00002605#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002606
drh6b9d6dd2008-12-03 19:34:47 +00002607/*
2608** This is a utility for setting or clearing a bit-range lock on an
2609** AFP filesystem.
2610**
2611** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2612*/
2613static int afpSetLock(
2614 const char *path, /* Name of the file to be locked or unlocked */
2615 unixFile *pFile, /* Open file descriptor on path */
2616 unsigned long long offset, /* First byte to be locked */
2617 unsigned long long length, /* Number of bytes to lock */
2618 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002619){
drh6b9d6dd2008-12-03 19:34:47 +00002620 struct ByteRangeLockPB2 pb;
2621 int err;
drhbfe66312006-10-03 17:40:40 +00002622
2623 pb.unLockFlag = setLockFlag ? 0 : 1;
2624 pb.startEndFlag = 0;
2625 pb.offset = offset;
2626 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002627 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002628
drh308c2a52010-05-14 11:30:18 +00002629 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002630 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002631 offset, length));
drhbfe66312006-10-03 17:40:40 +00002632 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2633 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002634 int rc;
2635 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002636 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2637 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002638#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2639 rc = SQLITE_BUSY;
2640#else
drh734c9862008-11-28 15:37:20 +00002641 rc = sqliteErrorFromPosixError(tErrno,
2642 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002643#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002644 if( IS_LOCK_ERROR(rc) ){
2645 pFile->lastErrno = tErrno;
2646 }
2647 return rc;
drhbfe66312006-10-03 17:40:40 +00002648 } else {
aswift5b1a2562008-08-22 00:22:35 +00002649 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002650 }
2651}
2652
drh6b9d6dd2008-12-03 19:34:47 +00002653/*
2654** This routine checks if there is a RESERVED lock held on the specified
2655** file by this or any other process. If such a lock is held, set *pResOut
2656** to a non-zero value otherwise *pResOut is set to zero. The return value
2657** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2658*/
danielk1977e339d652008-06-28 11:23:00 +00002659static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002660 int rc = SQLITE_OK;
2661 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002662 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002663 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002664
aswift5b1a2562008-08-22 00:22:35 +00002665 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2666
2667 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002668 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002669 if( context->reserved ){
2670 *pResOut = 1;
2671 return SQLITE_OK;
2672 }
drh8af6c222010-05-14 12:43:01 +00002673 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002674
2675 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002676 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002677 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002678 }
2679
2680 /* Otherwise see if some other process holds it.
2681 */
aswift5b1a2562008-08-22 00:22:35 +00002682 if( !reserved ){
2683 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002684 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002685 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002686 /* if we succeeded in taking the reserved lock, unlock it to restore
2687 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002688 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002689 } else {
2690 /* if we failed to get the lock then someone else must have it */
2691 reserved = 1;
2692 }
2693 if( IS_LOCK_ERROR(lrc) ){
2694 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002695 }
2696 }
drhbfe66312006-10-03 17:40:40 +00002697
drh7ed97b92010-01-20 13:07:21 +00002698 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002699 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002700
2701 *pResOut = reserved;
2702 return rc;
drhbfe66312006-10-03 17:40:40 +00002703}
2704
drh6b9d6dd2008-12-03 19:34:47 +00002705/*
drh308c2a52010-05-14 11:30:18 +00002706** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002707** of the following:
2708**
2709** (1) SHARED_LOCK
2710** (2) RESERVED_LOCK
2711** (3) PENDING_LOCK
2712** (4) EXCLUSIVE_LOCK
2713**
2714** Sometimes when requesting one lock state, additional lock states
2715** are inserted in between. The locking might fail on one of the later
2716** transitions leaving the lock state different from what it started but
2717** still short of its goal. The following chart shows the allowed
2718** transitions and the inserted intermediate states:
2719**
2720** UNLOCKED -> SHARED
2721** SHARED -> RESERVED
2722** SHARED -> (PENDING) -> EXCLUSIVE
2723** RESERVED -> (PENDING) -> EXCLUSIVE
2724** PENDING -> EXCLUSIVE
2725**
2726** This routine will only increase a lock. Use the sqlite3OsUnlock()
2727** routine to lower a locking level.
2728*/
drh308c2a52010-05-14 11:30:18 +00002729static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002730 int rc = SQLITE_OK;
2731 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002732 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002733 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002734
2735 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002736 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2737 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002738 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002739
drhbfe66312006-10-03 17:40:40 +00002740 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002741 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002742 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002743 */
drh308c2a52010-05-14 11:30:18 +00002744 if( pFile->eFileLock>=eFileLock ){
2745 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2746 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002747 return SQLITE_OK;
2748 }
2749
2750 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002751 ** (1) We never move from unlocked to anything higher than shared lock.
2752 ** (2) SQLite never explicitly requests a pendig lock.
2753 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002754 */
drh308c2a52010-05-14 11:30:18 +00002755 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2756 assert( eFileLock!=PENDING_LOCK );
2757 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002758
drh8af6c222010-05-14 12:43:01 +00002759 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002760 */
drh6c7d5c52008-11-21 20:32:33 +00002761 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002762 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002763
2764 /* If some thread using this PID has a lock via a different unixFile*
2765 ** handle that precludes the requested lock, return BUSY.
2766 */
drh8af6c222010-05-14 12:43:01 +00002767 if( (pFile->eFileLock!=pInode->eFileLock &&
2768 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002769 ){
2770 rc = SQLITE_BUSY;
2771 goto afp_end_lock;
2772 }
2773
2774 /* If a SHARED lock is requested, and some thread using this PID already
2775 ** has a SHARED or RESERVED lock, then increment reference counts and
2776 ** return SQLITE_OK.
2777 */
drh308c2a52010-05-14 11:30:18 +00002778 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002779 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002780 assert( eFileLock==SHARED_LOCK );
2781 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002782 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002783 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002784 pInode->nShared++;
2785 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002786 goto afp_end_lock;
2787 }
drhbfe66312006-10-03 17:40:40 +00002788
2789 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002790 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2791 ** be released.
2792 */
drh308c2a52010-05-14 11:30:18 +00002793 if( eFileLock==SHARED_LOCK
2794 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002795 ){
2796 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002797 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002798 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002799 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002800 goto afp_end_lock;
2801 }
2802 }
2803
2804 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002805 ** operating system calls for the specified lock.
2806 */
drh308c2a52010-05-14 11:30:18 +00002807 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002808 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002809 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002810
drh8af6c222010-05-14 12:43:01 +00002811 assert( pInode->nShared==0 );
2812 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002813
2814 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002815 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002816 /* note that the quality of the randomness doesn't matter that much */
2817 lk = random();
drh8af6c222010-05-14 12:43:01 +00002818 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002819 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002820 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002821 if( IS_LOCK_ERROR(lrc1) ){
2822 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002823 }
aswift5b1a2562008-08-22 00:22:35 +00002824 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002825 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002826
aswift5b1a2562008-08-22 00:22:35 +00002827 if( IS_LOCK_ERROR(lrc1) ) {
2828 pFile->lastErrno = lrc1Errno;
2829 rc = lrc1;
2830 goto afp_end_lock;
2831 } else if( IS_LOCK_ERROR(lrc2) ){
2832 rc = lrc2;
2833 goto afp_end_lock;
2834 } else if( lrc1 != SQLITE_OK ) {
2835 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002836 } else {
drh308c2a52010-05-14 11:30:18 +00002837 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002838 pInode->nLock++;
2839 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002840 }
drh8af6c222010-05-14 12:43:01 +00002841 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002842 /* We are trying for an exclusive lock but another thread in this
2843 ** same process is still holding a shared lock. */
2844 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002845 }else{
2846 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2847 ** assumed that there is a SHARED or greater lock on the file
2848 ** already.
2849 */
2850 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002851 assert( 0!=pFile->eFileLock );
2852 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002853 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002854 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002855 if( !failed ){
2856 context->reserved = 1;
2857 }
drhbfe66312006-10-03 17:40:40 +00002858 }
drh308c2a52010-05-14 11:30:18 +00002859 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002860 /* Acquire an EXCLUSIVE lock */
2861
2862 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002863 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002864 */
drh6b9d6dd2008-12-03 19:34:47 +00002865 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002866 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002867 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002868 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002869 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002870 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002871 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002872 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002873 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2874 ** a critical I/O error
2875 */
2876 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2877 SQLITE_IOERR_LOCK;
2878 goto afp_end_lock;
2879 }
2880 }else{
aswift5b1a2562008-08-22 00:22:35 +00002881 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002882 }
2883 }
aswift5b1a2562008-08-22 00:22:35 +00002884 if( failed ){
2885 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002886 }
2887 }
2888
2889 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002890 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002891 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002892 }else if( eFileLock==EXCLUSIVE_LOCK ){
2893 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002894 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002895 }
2896
2897afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002898 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002899 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2900 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002901 return rc;
2902}
2903
2904/*
drh308c2a52010-05-14 11:30:18 +00002905** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002906** must be either NO_LOCK or SHARED_LOCK.
2907**
2908** If the locking level of the file descriptor is already at or below
2909** the requested locking level, this routine is a no-op.
2910*/
drh308c2a52010-05-14 11:30:18 +00002911static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002912 int rc = SQLITE_OK;
2913 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002914 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002915 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2916 int skipShared = 0;
2917#ifdef SQLITE_TEST
2918 int h = pFile->h;
2919#endif
drhbfe66312006-10-03 17:40:40 +00002920
2921 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002922 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002923 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002924 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002925
drh308c2a52010-05-14 11:30:18 +00002926 assert( eFileLock<=SHARED_LOCK );
2927 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002928 return SQLITE_OK;
2929 }
drh6c7d5c52008-11-21 20:32:33 +00002930 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002931 pInode = pFile->pInode;
2932 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002933 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002934 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002935 SimulateIOErrorBenign(1);
2936 SimulateIOError( h=(-1) )
2937 SimulateIOErrorBenign(0);
2938
drhd3d8c042012-05-29 17:02:40 +00002939#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002940 /* When reducing a lock such that other processes can start
2941 ** reading the database file again, make sure that the
2942 ** transaction counter was updated if any part of the database
2943 ** file changed. If the transaction counter is not updated,
2944 ** other connections to the same file might not realize that
2945 ** the file has changed and hence might not know to flush their
2946 ** cache. The use of a stale cache can lead to database corruption.
2947 */
2948 assert( pFile->inNormalWrite==0
2949 || pFile->dbUpdate==0
2950 || pFile->transCntrChng==1 );
2951 pFile->inNormalWrite = 0;
2952#endif
aswiftaebf4132008-11-21 00:10:35 +00002953
drh308c2a52010-05-14 11:30:18 +00002954 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002955 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002956 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002957 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002958 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002959 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2960 } else {
2961 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002962 }
2963 }
drh308c2a52010-05-14 11:30:18 +00002964 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002965 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002966 }
drh308c2a52010-05-14 11:30:18 +00002967 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002968 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2969 if( !rc ){
2970 context->reserved = 0;
2971 }
aswiftaebf4132008-11-21 00:10:35 +00002972 }
drh8af6c222010-05-14 12:43:01 +00002973 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2974 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002975 }
aswiftaebf4132008-11-21 00:10:35 +00002976 }
drh308c2a52010-05-14 11:30:18 +00002977 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002978
drh7ed97b92010-01-20 13:07:21 +00002979 /* Decrement the shared lock counter. Release the lock using an
2980 ** OS call only when all threads in this same process have released
2981 ** the lock.
2982 */
drh8af6c222010-05-14 12:43:01 +00002983 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2984 pInode->nShared--;
2985 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002986 SimulateIOErrorBenign(1);
2987 SimulateIOError( h=(-1) )
2988 SimulateIOErrorBenign(0);
2989 if( !skipShared ){
2990 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2991 }
2992 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002993 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002994 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002995 }
2996 }
2997 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002998 pInode->nLock--;
2999 assert( pInode->nLock>=0 );
3000 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003001 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003002 }
3003 }
drhbfe66312006-10-03 17:40:40 +00003004 }
drh7ed97b92010-01-20 13:07:21 +00003005
drh6c7d5c52008-11-21 20:32:33 +00003006 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003007 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003008 return rc;
3009}
3010
3011/*
drh339eb0b2008-03-07 15:34:11 +00003012** Close a file & cleanup AFP specific locking context
3013*/
danielk1977e339d652008-06-28 11:23:00 +00003014static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003015 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003016 if( id ){
3017 unixFile *pFile = (unixFile*)id;
3018 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003019 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003020 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003021 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003022 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003023 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003024 ** the last lock is cleared.
3025 */
dan08da86a2009-08-21 17:18:03 +00003026 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003027 }
danb0ac3e32010-06-16 10:55:42 +00003028 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003029 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003030 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003031 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003032 }
drh7ed97b92010-01-20 13:07:21 +00003033 return rc;
drhbfe66312006-10-03 17:40:40 +00003034}
3035
drhd2cb50b2009-01-09 21:41:17 +00003036#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003037/*
3038** The code above is the AFP lock implementation. The code is specific
3039** to MacOSX and does not work on other unix platforms. No alternative
3040** is available. If you don't compile for a mac, then the "unix-afp"
3041** VFS is not available.
3042**
3043********************* End of the AFP lock implementation **********************
3044******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003045
drh7ed97b92010-01-20 13:07:21 +00003046/******************************************************************************
3047*************************** Begin NFS Locking ********************************/
3048
3049#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3050/*
drh308c2a52010-05-14 11:30:18 +00003051 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003052 ** must be either NO_LOCK or SHARED_LOCK.
3053 **
3054 ** If the locking level of the file descriptor is already at or below
3055 ** the requested locking level, this routine is a no-op.
3056 */
drh308c2a52010-05-14 11:30:18 +00003057static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003058 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003059}
3060
3061#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3062/*
3063** The code above is the NFS lock implementation. The code is specific
3064** to MacOSX and does not work on other unix platforms. No alternative
3065** is available.
3066**
3067********************* End of the NFS lock implementation **********************
3068******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003069
3070/******************************************************************************
3071**************** Non-locking sqlite3_file methods *****************************
3072**
3073** The next division contains implementations for all methods of the
3074** sqlite3_file object other than the locking methods. The locking
3075** methods were defined in divisions above (one locking method per
3076** division). Those methods that are common to all locking modes
3077** are gather together into this division.
3078*/
drhbfe66312006-10-03 17:40:40 +00003079
3080/*
drh734c9862008-11-28 15:37:20 +00003081** Seek to the offset passed as the second argument, then read cnt
3082** bytes into pBuf. Return the number of bytes actually read.
3083**
3084** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3085** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3086** one system to another. Since SQLite does not define USE_PREAD
3087** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3088** See tickets #2741 and #2681.
3089**
3090** To avoid stomping the errno value on a failed read the lastErrno value
3091** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003092*/
drh734c9862008-11-28 15:37:20 +00003093static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3094 int got;
drh58024642011-11-07 18:16:00 +00003095 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003096#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003097 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003098#endif
drh734c9862008-11-28 15:37:20 +00003099 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003100 assert( cnt==(cnt&0x1ffff) );
3101 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003102 do{
drh734c9862008-11-28 15:37:20 +00003103#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003104 got = osPread(id->h, pBuf, cnt, offset);
3105 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003106#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003107 got = osPread64(id->h, pBuf, cnt, offset);
3108 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003109#else
drh58024642011-11-07 18:16:00 +00003110 newOffset = lseek(id->h, offset, SEEK_SET);
3111 SimulateIOError( newOffset-- );
3112 if( newOffset!=offset ){
3113 if( newOffset == -1 ){
3114 ((unixFile*)id)->lastErrno = errno;
3115 }else{
drhf2f105d2012-08-20 15:53:54 +00003116 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003117 }
3118 return -1;
drh734c9862008-11-28 15:37:20 +00003119 }
drh58024642011-11-07 18:16:00 +00003120 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003121#endif
drh58024642011-11-07 18:16:00 +00003122 if( got==cnt ) break;
3123 if( got<0 ){
3124 if( errno==EINTR ){ got = 1; continue; }
3125 prior = 0;
3126 ((unixFile*)id)->lastErrno = errno;
3127 break;
3128 }else if( got>0 ){
3129 cnt -= got;
3130 offset += got;
3131 prior += got;
3132 pBuf = (void*)(got + (char*)pBuf);
3133 }
3134 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003135 TIMER_END;
drh58024642011-11-07 18:16:00 +00003136 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3137 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3138 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003139}
3140
3141/*
drh734c9862008-11-28 15:37:20 +00003142** Read data from a file into a buffer. Return SQLITE_OK if all
3143** bytes were read successfully and SQLITE_IOERR if anything goes
3144** wrong.
drh339eb0b2008-03-07 15:34:11 +00003145*/
drh734c9862008-11-28 15:37:20 +00003146static int unixRead(
3147 sqlite3_file *id,
3148 void *pBuf,
3149 int amt,
3150 sqlite3_int64 offset
3151){
dan08da86a2009-08-21 17:18:03 +00003152 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003153 int got;
3154 assert( id );
drh08c6d442009-02-09 17:34:07 +00003155
dan08da86a2009-08-21 17:18:03 +00003156 /* If this is a database file (not a journal, master-journal or temp
3157 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003158#if 0
dane946c392009-08-22 11:39:46 +00003159 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003160 || offset>=PENDING_BYTE+512
3161 || offset+amt<=PENDING_BYTE
3162 );
dan7c246102010-04-12 19:00:29 +00003163#endif
drh08c6d442009-02-09 17:34:07 +00003164
drh9b4c59f2013-04-15 17:03:42 +00003165#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003166 /* Deal with as much of this read request as possible by transfering
3167 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003168 if( offset<pFile->mmapSize ){
3169 if( offset+amt <= pFile->mmapSize ){
3170 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3171 return SQLITE_OK;
3172 }else{
3173 int nCopy = pFile->mmapSize - offset;
3174 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3175 pBuf = &((u8 *)pBuf)[nCopy];
3176 amt -= nCopy;
3177 offset += nCopy;
3178 }
3179 }
drh6e0b6d52013-04-09 16:19:20 +00003180#endif
danf23da962013-03-23 21:00:41 +00003181
dan08da86a2009-08-21 17:18:03 +00003182 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003183 if( got==amt ){
3184 return SQLITE_OK;
3185 }else if( got<0 ){
3186 /* lastErrno set by seekAndRead */
3187 return SQLITE_IOERR_READ;
3188 }else{
dan08da86a2009-08-21 17:18:03 +00003189 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003190 /* Unread parts of the buffer must be zero-filled */
3191 memset(&((char*)pBuf)[got], 0, amt-got);
3192 return SQLITE_IOERR_SHORT_READ;
3193 }
3194}
3195
3196/*
3197** Seek to the offset in id->offset then read cnt bytes into pBuf.
3198** Return the number of bytes actually read. Update the offset.
3199**
3200** To avoid stomping the errno value on a failed write the lastErrno value
3201** is set before returning.
3202*/
3203static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3204 int got;
drh7ed97b92010-01-20 13:07:21 +00003205#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003206 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003207#endif
drhc1fd2cf2012-10-01 12:16:26 +00003208 assert( cnt==(cnt&0x1ffff) );
3209 cnt &= 0x1ffff;
drh734c9862008-11-28 15:37:20 +00003210 TIMER_START;
3211#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003212 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003213#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003214 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003215#else
drhbd1e50c2011-08-19 14:54:12 +00003216 do{
3217 newOffset = lseek(id->h, offset, SEEK_SET);
3218 SimulateIOError( newOffset-- );
3219 if( newOffset!=offset ){
3220 if( newOffset == -1 ){
3221 ((unixFile*)id)->lastErrno = errno;
3222 }else{
drhf2f105d2012-08-20 15:53:54 +00003223 ((unixFile*)id)->lastErrno = 0;
drhbd1e50c2011-08-19 14:54:12 +00003224 }
3225 return -1;
drh734c9862008-11-28 15:37:20 +00003226 }
drhbd1e50c2011-08-19 14:54:12 +00003227 got = osWrite(id->h, pBuf, cnt);
3228 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003229#endif
3230 TIMER_END;
3231 if( got<0 ){
3232 ((unixFile*)id)->lastErrno = errno;
3233 }
3234
drh308c2a52010-05-14 11:30:18 +00003235 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003236 return got;
3237}
3238
3239
3240/*
3241** Write data from a buffer into a file. Return SQLITE_OK on success
3242** or some other error code on failure.
3243*/
3244static int unixWrite(
3245 sqlite3_file *id,
3246 const void *pBuf,
3247 int amt,
3248 sqlite3_int64 offset
3249){
dan08da86a2009-08-21 17:18:03 +00003250 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003251 int wrote = 0;
3252 assert( id );
3253 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003254
dan08da86a2009-08-21 17:18:03 +00003255 /* If this is a database file (not a journal, master-journal or temp
3256 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003257#if 0
dane946c392009-08-22 11:39:46 +00003258 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003259 || offset>=PENDING_BYTE+512
3260 || offset+amt<=PENDING_BYTE
3261 );
dan7c246102010-04-12 19:00:29 +00003262#endif
drh08c6d442009-02-09 17:34:07 +00003263
drhd3d8c042012-05-29 17:02:40 +00003264#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003265 /* If we are doing a normal write to a database file (as opposed to
3266 ** doing a hot-journal rollback or a write to some file other than a
3267 ** normal database file) then record the fact that the database
3268 ** has changed. If the transaction counter is modified, record that
3269 ** fact too.
3270 */
dan08da86a2009-08-21 17:18:03 +00003271 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003272 pFile->dbUpdate = 1; /* The database has been modified */
3273 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003274 int rc;
drh8f941bc2009-01-14 23:03:40 +00003275 char oldCntr[4];
3276 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003277 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003278 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003279 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003280 pFile->transCntrChng = 1; /* The transaction counter has changed */
3281 }
3282 }
3283 }
3284#endif
3285
drh9b4c59f2013-04-15 17:03:42 +00003286#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003287 /* Deal with as much of this write request as possible by transfering
3288 ** data from the memory mapping using memcpy(). */
3289 if( offset<pFile->mmapSize ){
3290 if( offset+amt <= pFile->mmapSize ){
3291 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3292 return SQLITE_OK;
3293 }else{
3294 int nCopy = pFile->mmapSize - offset;
3295 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3296 pBuf = &((u8 *)pBuf)[nCopy];
3297 amt -= nCopy;
3298 offset += nCopy;
3299 }
3300 }
drh6e0b6d52013-04-09 16:19:20 +00003301#endif
danf23da962013-03-23 21:00:41 +00003302
dan08da86a2009-08-21 17:18:03 +00003303 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003304 amt -= wrote;
3305 offset += wrote;
3306 pBuf = &((char*)pBuf)[wrote];
3307 }
3308 SimulateIOError(( wrote=(-1), amt=1 ));
3309 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003310
drh734c9862008-11-28 15:37:20 +00003311 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003312 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003313 /* lastErrno set by seekAndWrite */
3314 return SQLITE_IOERR_WRITE;
3315 }else{
dan08da86a2009-08-21 17:18:03 +00003316 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003317 return SQLITE_FULL;
3318 }
3319 }
dan6e09d692010-07-27 18:34:15 +00003320
drh734c9862008-11-28 15:37:20 +00003321 return SQLITE_OK;
3322}
3323
3324#ifdef SQLITE_TEST
3325/*
3326** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003327** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003328*/
3329int sqlite3_sync_count = 0;
3330int sqlite3_fullsync_count = 0;
3331#endif
3332
3333/*
drh89240432009-03-25 01:06:01 +00003334** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003335** Others do no. To be safe, we will stick with the (slightly slower)
3336** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003337** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003338*/
drh20f8e132011-08-31 21:01:55 +00003339#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003340# define fdatasync fsync
3341#endif
3342
3343/*
3344** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3345** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3346** only available on Mac OS X. But that could change.
3347*/
3348#ifdef F_FULLFSYNC
3349# define HAVE_FULLFSYNC 1
3350#else
3351# define HAVE_FULLFSYNC 0
3352#endif
3353
3354
3355/*
3356** The fsync() system call does not work as advertised on many
3357** unix systems. The following procedure is an attempt to make
3358** it work better.
3359**
3360** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3361** for testing when we want to run through the test suite quickly.
3362** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3363** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3364** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003365**
3366** SQLite sets the dataOnly flag if the size of the file is unchanged.
3367** The idea behind dataOnly is that it should only write the file content
3368** to disk, not the inode. We only set dataOnly if the file size is
3369** unchanged since the file size is part of the inode. However,
3370** Ted Ts'o tells us that fdatasync() will also write the inode if the
3371** file size has changed. The only real difference between fdatasync()
3372** and fsync(), Ted tells us, is that fdatasync() will not flush the
3373** inode if the mtime or owner or other inode attributes have changed.
3374** We only care about the file size, not the other file attributes, so
3375** as far as SQLite is concerned, an fdatasync() is always adequate.
3376** So, we always use fdatasync() if it is available, regardless of
3377** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003378*/
3379static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003380 int rc;
drh734c9862008-11-28 15:37:20 +00003381
3382 /* The following "ifdef/elif/else/" block has the same structure as
3383 ** the one below. It is replicated here solely to avoid cluttering
3384 ** up the real code with the UNUSED_PARAMETER() macros.
3385 */
3386#ifdef SQLITE_NO_SYNC
3387 UNUSED_PARAMETER(fd);
3388 UNUSED_PARAMETER(fullSync);
3389 UNUSED_PARAMETER(dataOnly);
3390#elif HAVE_FULLFSYNC
3391 UNUSED_PARAMETER(dataOnly);
3392#else
3393 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003394 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003395#endif
3396
3397 /* Record the number of times that we do a normal fsync() and
3398 ** FULLSYNC. This is used during testing to verify that this procedure
3399 ** gets called with the correct arguments.
3400 */
3401#ifdef SQLITE_TEST
3402 if( fullSync ) sqlite3_fullsync_count++;
3403 sqlite3_sync_count++;
3404#endif
3405
3406 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3407 ** no-op
3408 */
3409#ifdef SQLITE_NO_SYNC
3410 rc = SQLITE_OK;
3411#elif HAVE_FULLFSYNC
3412 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003413 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003414 }else{
3415 rc = 1;
3416 }
3417 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003418 ** It shouldn't be possible for fullfsync to fail on the local
3419 ** file system (on OSX), so failure indicates that FULLFSYNC
3420 ** isn't supported for this file system. So, attempt an fsync
3421 ** and (for now) ignore the overhead of a superfluous fcntl call.
3422 ** It'd be better to detect fullfsync support once and avoid
3423 ** the fcntl call every time sync is called.
3424 */
drh734c9862008-11-28 15:37:20 +00003425 if( rc ) rc = fsync(fd);
3426
drh7ed97b92010-01-20 13:07:21 +00003427#elif defined(__APPLE__)
3428 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3429 ** so currently we default to the macro that redefines fdatasync to fsync
3430 */
3431 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003432#else
drh0b647ff2009-03-21 14:41:04 +00003433 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003434#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003435 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003436 rc = fsync(fd);
3437 }
drh0b647ff2009-03-21 14:41:04 +00003438#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003439#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3440
3441 if( OS_VXWORKS && rc!= -1 ){
3442 rc = 0;
3443 }
chw97185482008-11-17 08:05:31 +00003444 return rc;
drhbfe66312006-10-03 17:40:40 +00003445}
3446
drh734c9862008-11-28 15:37:20 +00003447/*
drh0059eae2011-08-08 23:48:40 +00003448** Open a file descriptor to the directory containing file zFilename.
3449** If successful, *pFd is set to the opened file descriptor and
3450** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3451** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3452** value.
3453**
drh90315a22011-08-10 01:52:12 +00003454** The directory file descriptor is used for only one thing - to
3455** fsync() a directory to make sure file creation and deletion events
3456** are flushed to disk. Such fsyncs are not needed on newer
3457** journaling filesystems, but are required on older filesystems.
3458**
3459** This routine can be overridden using the xSetSysCall interface.
3460** The ability to override this routine was added in support of the
3461** chromium sandbox. Opening a directory is a security risk (we are
3462** told) so making it overrideable allows the chromium sandbox to
3463** replace this routine with a harmless no-op. To make this routine
3464** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3465** *pFd set to a negative number.
3466**
drh0059eae2011-08-08 23:48:40 +00003467** If SQLITE_OK is returned, the caller is responsible for closing
3468** the file descriptor *pFd using close().
3469*/
3470static int openDirectory(const char *zFilename, int *pFd){
3471 int ii;
3472 int fd = -1;
3473 char zDirname[MAX_PATHNAME+1];
3474
3475 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3476 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3477 if( ii>0 ){
3478 zDirname[ii] = '\0';
3479 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3480 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003481 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3482 }
3483 }
3484 *pFd = fd;
3485 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3486}
3487
3488/*
drh734c9862008-11-28 15:37:20 +00003489** Make sure all writes to a particular file are committed to disk.
3490**
3491** If dataOnly==0 then both the file itself and its metadata (file
3492** size, access time, etc) are synced. If dataOnly!=0 then only the
3493** file data is synced.
3494**
3495** Under Unix, also make sure that the directory entry for the file
3496** has been created by fsync-ing the directory that contains the file.
3497** If we do not do this and we encounter a power failure, the directory
3498** entry for the journal might not exist after we reboot. The next
3499** SQLite to access the file will not know that the journal exists (because
3500** the directory entry for the journal was never created) and the transaction
3501** will not roll back - possibly leading to database corruption.
3502*/
3503static int unixSync(sqlite3_file *id, int flags){
3504 int rc;
3505 unixFile *pFile = (unixFile*)id;
3506
3507 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3508 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3509
3510 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3511 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3512 || (flags&0x0F)==SQLITE_SYNC_FULL
3513 );
3514
3515 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3516 ** line is to test that doing so does not cause any problems.
3517 */
3518 SimulateDiskfullError( return SQLITE_FULL );
3519
3520 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003521 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003522 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3523 SimulateIOError( rc=1 );
3524 if( rc ){
3525 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003526 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003527 }
drh0059eae2011-08-08 23:48:40 +00003528
3529 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003530 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003531 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003532 */
3533 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3534 int dirfd;
3535 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003536 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003537 rc = osOpenDirectory(pFile->zPath, &dirfd);
3538 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003539 full_fsync(dirfd, 0, 0);
3540 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003541 }else if( rc==SQLITE_CANTOPEN ){
3542 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003543 }
drh0059eae2011-08-08 23:48:40 +00003544 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003545 }
3546 return rc;
3547}
3548
3549/*
3550** Truncate an open file to a specified size
3551*/
3552static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003553 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003554 int rc;
dan6e09d692010-07-27 18:34:15 +00003555 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003556 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003557
3558 /* If the user has configured a chunk-size for this file, truncate the
3559 ** file so that it consists of an integer number of chunks (i.e. the
3560 ** actual file size after the operation may be larger than the requested
3561 ** size).
3562 */
drhb8af4b72012-04-05 20:04:39 +00003563 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003564 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3565 }
3566
drhff812312011-02-23 13:33:46 +00003567 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003568 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003569 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003570 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003571 }else{
drhd3d8c042012-05-29 17:02:40 +00003572#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003573 /* If we are doing a normal write to a database file (as opposed to
3574 ** doing a hot-journal rollback or a write to some file other than a
3575 ** normal database file) and we truncate the file to zero length,
3576 ** that effectively updates the change counter. This might happen
3577 ** when restoring a database using the backup API from a zero-length
3578 ** source.
3579 */
dan6e09d692010-07-27 18:34:15 +00003580 if( pFile->inNormalWrite && nByte==0 ){
3581 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003582 }
danf23da962013-03-23 21:00:41 +00003583#endif
danc0003312013-03-22 17:46:11 +00003584
3585 /* If the file was just truncated to a size smaller than the currently
3586 ** mapped region, reduce the effective mapping size as well. SQLite will
3587 ** use read() and write() to access data beyond this point from now on.
3588 */
3589 if( nByte<pFile->mmapSize ){
3590 pFile->mmapSize = nByte;
3591 }
drh3313b142009-11-06 04:13:18 +00003592
drh734c9862008-11-28 15:37:20 +00003593 return SQLITE_OK;
3594 }
3595}
3596
3597/*
3598** Determine the current size of a file in bytes
3599*/
3600static int unixFileSize(sqlite3_file *id, i64 *pSize){
3601 int rc;
3602 struct stat buf;
3603 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003604 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003605 SimulateIOError( rc=1 );
3606 if( rc!=0 ){
3607 ((unixFile*)id)->lastErrno = errno;
3608 return SQLITE_IOERR_FSTAT;
3609 }
3610 *pSize = buf.st_size;
3611
drh8af6c222010-05-14 12:43:01 +00003612 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003613 ** writes a single byte into that file in order to work around a bug
3614 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3615 ** layers, we need to report this file size as zero even though it is
3616 ** really 1. Ticket #3260.
3617 */
3618 if( *pSize==1 ) *pSize = 0;
3619
3620
3621 return SQLITE_OK;
3622}
3623
drhd2cb50b2009-01-09 21:41:17 +00003624#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003625/*
3626** Handler for proxy-locking file-control verbs. Defined below in the
3627** proxying locking division.
3628*/
3629static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003630#endif
drh715ff302008-12-03 22:32:44 +00003631
dan502019c2010-07-28 14:26:17 +00003632/*
3633** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003634** file-control operation. Enlarge the database to nBytes in size
3635** (rounded up to the next chunk-size). If the database is already
3636** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003637*/
3638static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003639 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003640 i64 nSize; /* Required file size */
3641 struct stat buf; /* Used to hold return values of fstat() */
3642
drh99ab3b12011-03-02 15:09:07 +00003643 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003644
3645 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3646 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003647
dan502019c2010-07-28 14:26:17 +00003648#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003649 /* The code below is handling the return value of osFallocate()
3650 ** correctly. posix_fallocate() is defined to "returns zero on success,
3651 ** or an error number on failure". See the manpage for details. */
3652 int err;
drhff812312011-02-23 13:33:46 +00003653 do{
dan661d71a2011-03-30 19:08:03 +00003654 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3655 }while( err==EINTR );
3656 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003657#else
3658 /* If the OS does not have posix_fallocate(), fake it. First use
3659 ** ftruncate() to set the file size, then write a single byte to
3660 ** the last byte in each block within the extended region. This
3661 ** is the same technique used by glibc to implement posix_fallocate()
3662 ** on systems that do not have a real fallocate() system call.
3663 */
3664 int nBlk = buf.st_blksize; /* File-system block size */
3665 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003666
drhff812312011-02-23 13:33:46 +00003667 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003668 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003669 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003670 }
3671 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003672 while( iWrite<nSize ){
3673 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3674 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003675 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003676 }
dan502019c2010-07-28 14:26:17 +00003677#endif
3678 }
3679 }
3680
drh9b4c59f2013-04-15 17:03:42 +00003681 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003682 int rc;
3683 if( pFile->szChunk<=0 ){
3684 if( robust_ftruncate(pFile->h, nByte) ){
3685 pFile->lastErrno = errno;
3686 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3687 }
3688 }
3689
3690 rc = unixMapfile(pFile, nByte);
3691 return rc;
3692 }
3693
dan502019c2010-07-28 14:26:17 +00003694 return SQLITE_OK;
3695}
danielk1977ad94b582007-08-20 06:44:22 +00003696
danielk1977e3026632004-06-22 11:29:02 +00003697/*
drhf12b3f62011-12-21 14:42:29 +00003698** If *pArg is inititially negative then this is a query. Set *pArg to
3699** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3700**
3701** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3702*/
3703static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3704 if( *pArg<0 ){
3705 *pArg = (pFile->ctrlFlags & mask)!=0;
3706 }else if( (*pArg)==0 ){
3707 pFile->ctrlFlags &= ~mask;
3708 }else{
3709 pFile->ctrlFlags |= mask;
3710 }
3711}
3712
drh696b33e2012-12-06 19:01:42 +00003713/* Forward declaration */
3714static int unixGetTempname(int nBuf, char *zBuf);
3715
drhf12b3f62011-12-21 14:42:29 +00003716/*
drh9e33c2c2007-08-31 18:34:59 +00003717** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003718*/
drhcc6bb3e2007-08-31 16:11:35 +00003719static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003720 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003721 switch( op ){
3722 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003723 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003724 return SQLITE_OK;
3725 }
drh7708e972008-11-29 00:56:52 +00003726 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003727 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003728 return SQLITE_OK;
3729 }
dan6e09d692010-07-27 18:34:15 +00003730 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003731 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003732 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003733 }
drh9ff27ec2010-05-19 19:26:05 +00003734 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003735 int rc;
3736 SimulateIOErrorBenign(1);
3737 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3738 SimulateIOErrorBenign(0);
3739 return rc;
drhf0b190d2011-07-26 16:03:07 +00003740 }
3741 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003742 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3743 return SQLITE_OK;
3744 }
drhcb15f352011-12-23 01:04:17 +00003745 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3746 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003747 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003748 }
drhde60fc22011-12-14 17:53:36 +00003749 case SQLITE_FCNTL_VFSNAME: {
3750 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3751 return SQLITE_OK;
3752 }
drh696b33e2012-12-06 19:01:42 +00003753 case SQLITE_FCNTL_TEMPFILENAME: {
3754 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3755 if( zTFile ){
3756 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3757 *(char**)pArg = zTFile;
3758 }
3759 return SQLITE_OK;
3760 }
drh9b4c59f2013-04-15 17:03:42 +00003761 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003762 i64 newLimit = *(i64*)pArg;
drh9b4c59f2013-04-15 17:03:42 +00003763 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3764 newLimit = sqlite3GlobalConfig.mxMmap;
3765 }
3766 *(i64*)pArg = pFile->mmapSizeMax;
danbcb8a862013-04-08 15:30:41 +00003767 if( newLimit>=0 ){
drh9b4c59f2013-04-15 17:03:42 +00003768 pFile->mmapSizeMax = newLimit;
danbcb8a862013-04-08 15:30:41 +00003769 if( newLimit<pFile->mmapSize ) pFile->mmapSize = newLimit;
3770 }
danb2d3de32013-03-14 18:34:37 +00003771 return SQLITE_OK;
3772 }
drhd3d8c042012-05-29 17:02:40 +00003773#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003774 /* The pager calls this method to signal that it has done
3775 ** a rollback and that the database is therefore unchanged and
3776 ** it hence it is OK for the transaction change counter to be
3777 ** unchanged.
3778 */
3779 case SQLITE_FCNTL_DB_UNCHANGED: {
3780 ((unixFile*)id)->dbUpdate = 0;
3781 return SQLITE_OK;
3782 }
3783#endif
drhd2cb50b2009-01-09 21:41:17 +00003784#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003785 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003786 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003787 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003788 }
drhd2cb50b2009-01-09 21:41:17 +00003789#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003790 }
drh0b52b7d2011-01-26 19:46:22 +00003791 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003792}
3793
3794/*
danielk1977a3d4c882007-03-23 10:08:38 +00003795** Return the sector size in bytes of the underlying block device for
3796** the specified file. This is almost always 512 bytes, but may be
3797** larger for some devices.
3798**
3799** SQLite code assumes this function cannot fail. It also assumes that
3800** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003801** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003802** same for both.
3803*/
drh537dddf2012-10-26 13:46:24 +00003804#ifndef __QNXNTO__
3805static int unixSectorSize(sqlite3_file *NotUsed){
3806 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003807 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003808}
drh537dddf2012-10-26 13:46:24 +00003809#endif
3810
3811/*
3812** The following version of unixSectorSize() is optimized for QNX.
3813*/
3814#ifdef __QNXNTO__
3815#include <sys/dcmd_blk.h>
3816#include <sys/statvfs.h>
3817static int unixSectorSize(sqlite3_file *id){
3818 unixFile *pFile = (unixFile*)id;
3819 if( pFile->sectorSize == 0 ){
3820 struct statvfs fsInfo;
3821
3822 /* Set defaults for non-supported filesystems */
3823 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3824 pFile->deviceCharacteristics = 0;
3825 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3826 return pFile->sectorSize;
3827 }
3828
3829 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3830 pFile->sectorSize = fsInfo.f_bsize;
3831 pFile->deviceCharacteristics =
3832 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3833 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3834 ** the write succeeds */
3835 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3836 ** so it is ordered */
3837 0;
3838 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3839 pFile->sectorSize = fsInfo.f_bsize;
3840 pFile->deviceCharacteristics =
3841 /* etfs cluster size writes are atomic */
3842 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3843 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3844 ** the write succeeds */
3845 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3846 ** so it is ordered */
3847 0;
3848 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3849 pFile->sectorSize = fsInfo.f_bsize;
3850 pFile->deviceCharacteristics =
3851 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3852 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3853 ** the write succeeds */
3854 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3855 ** so it is ordered */
3856 0;
3857 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3858 pFile->sectorSize = fsInfo.f_bsize;
3859 pFile->deviceCharacteristics =
3860 /* full bitset of atomics from max sector size and smaller */
3861 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3862 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3863 ** so it is ordered */
3864 0;
3865 }else if( strstr(fsInfo.f_basetype, "dos") ){
3866 pFile->sectorSize = fsInfo.f_bsize;
3867 pFile->deviceCharacteristics =
3868 /* full bitset of atomics from max sector size and smaller */
3869 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3870 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3871 ** so it is ordered */
3872 0;
3873 }else{
3874 pFile->deviceCharacteristics =
3875 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3876 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3877 ** the write succeeds */
3878 0;
3879 }
3880 }
3881 /* Last chance verification. If the sector size isn't a multiple of 512
3882 ** then it isn't valid.*/
3883 if( pFile->sectorSize % 512 != 0 ){
3884 pFile->deviceCharacteristics = 0;
3885 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3886 }
3887 return pFile->sectorSize;
3888}
3889#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003890
danielk197790949c22007-08-17 16:50:38 +00003891/*
drhf12b3f62011-12-21 14:42:29 +00003892** Return the device characteristics for the file.
3893**
drhcb15f352011-12-23 01:04:17 +00003894** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3895** However, that choice is contraversial since technically the underlying
3896** file system does not always provide powersafe overwrites. (In other
3897** words, after a power-loss event, parts of the file that were never
3898** written might end up being altered.) However, non-PSOW behavior is very,
3899** very rare. And asserting PSOW makes a large reduction in the amount
3900** of required I/O for journaling, since a lot of padding is eliminated.
3901** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3902** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003903*/
drhf12b3f62011-12-21 14:42:29 +00003904static int unixDeviceCharacteristics(sqlite3_file *id){
3905 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003906 int rc = 0;
3907#ifdef __QNXNTO__
3908 if( p->sectorSize==0 ) unixSectorSize(id);
3909 rc = p->deviceCharacteristics;
3910#endif
drhcb15f352011-12-23 01:04:17 +00003911 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003912 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003913 }
drh537dddf2012-10-26 13:46:24 +00003914 return rc;
danielk197762079062007-08-15 17:08:46 +00003915}
3916
drhd9e5c4f2010-05-12 18:01:39 +00003917#ifndef SQLITE_OMIT_WAL
3918
3919
3920/*
drhd91c68f2010-05-14 14:52:25 +00003921** Object used to represent an shared memory buffer.
3922**
3923** When multiple threads all reference the same wal-index, each thread
3924** has its own unixShm object, but they all point to a single instance
3925** of this unixShmNode object. In other words, each wal-index is opened
3926** only once per process.
3927**
3928** Each unixShmNode object is connected to a single unixInodeInfo object.
3929** We could coalesce this object into unixInodeInfo, but that would mean
3930** every open file that does not use shared memory (in other words, most
3931** open files) would have to carry around this extra information. So
3932** the unixInodeInfo object contains a pointer to this unixShmNode object
3933** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003934**
3935** unixMutexHeld() must be true when creating or destroying
3936** this object or while reading or writing the following fields:
3937**
3938** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003939**
3940** The following fields are read-only after the object is created:
3941**
3942** fid
3943** zFilename
3944**
drhd91c68f2010-05-14 14:52:25 +00003945** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003946** unixMutexHeld() is true when reading or writing any other field
3947** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003948*/
drhd91c68f2010-05-14 14:52:25 +00003949struct unixShmNode {
3950 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003951 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003952 char *zFilename; /* Name of the mmapped file */
3953 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003954 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003955 u16 nRegion; /* Size of array apRegion */
3956 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003957 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003958 int nRef; /* Number of unixShm objects pointing to this */
3959 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003960#ifdef SQLITE_DEBUG
3961 u8 exclMask; /* Mask of exclusive locks held */
3962 u8 sharedMask; /* Mask of shared locks held */
3963 u8 nextShmId; /* Next available unixShm.id value */
3964#endif
3965};
3966
3967/*
drhd9e5c4f2010-05-12 18:01:39 +00003968** Structure used internally by this VFS to record the state of an
3969** open shared memory connection.
3970**
drhd91c68f2010-05-14 14:52:25 +00003971** The following fields are initialized when this object is created and
3972** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003973**
drhd91c68f2010-05-14 14:52:25 +00003974** unixShm.pFile
3975** unixShm.id
3976**
3977** All other fields are read/write. The unixShm.pFile->mutex must be held
3978** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003979*/
3980struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003981 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3982 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003983 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003984 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003985 u16 sharedMask; /* Mask of shared locks held */
3986 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003987};
3988
3989/*
drhd9e5c4f2010-05-12 18:01:39 +00003990** Constants used for locking
3991*/
drhbd9676c2010-06-23 17:58:38 +00003992#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003993#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003994
drhd9e5c4f2010-05-12 18:01:39 +00003995/*
drh73b64e42010-05-30 19:55:15 +00003996** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003997**
3998** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3999** otherwise.
4000*/
4001static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004002 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4003 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004004 int ofst, /* First byte of the locking range */
4005 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004006){
4007 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004008 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004009
drhd91c68f2010-05-14 14:52:25 +00004010 /* Access to the unixShmNode object is serialized by the caller */
4011 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004012
drh73b64e42010-05-30 19:55:15 +00004013 /* Shared locks never span more than one byte */
4014 assert( n==1 || lockType!=F_RDLCK );
4015
4016 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004017 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004018
drh3cb93392011-03-12 18:10:44 +00004019 if( pShmNode->h>=0 ){
4020 /* Initialize the locking parameters */
4021 memset(&f, 0, sizeof(f));
4022 f.l_type = lockType;
4023 f.l_whence = SEEK_SET;
4024 f.l_start = ofst;
4025 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004026
drh3cb93392011-03-12 18:10:44 +00004027 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4028 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4029 }
drhd9e5c4f2010-05-12 18:01:39 +00004030
4031 /* Update the global lock state and do debug tracing */
4032#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004033 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004034 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00004035 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004036 if( rc==SQLITE_OK ){
4037 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004038 OSTRACE(("unlock %d ok", ofst));
4039 pShmNode->exclMask &= ~mask;
4040 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004041 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004042 OSTRACE(("read-lock %d ok", ofst));
4043 pShmNode->exclMask &= ~mask;
4044 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004045 }else{
4046 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004047 OSTRACE(("write-lock %d ok", ofst));
4048 pShmNode->exclMask |= mask;
4049 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004050 }
4051 }else{
4052 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004053 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004054 }else if( lockType==F_RDLCK ){
4055 OSTRACE(("read-lock failed"));
4056 }else{
4057 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004058 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004059 }
4060 }
drh20e1f082010-05-31 16:10:12 +00004061 OSTRACE((" - afterwards %03x,%03x\n",
4062 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004063 }
drhd9e5c4f2010-05-12 18:01:39 +00004064#endif
4065
4066 return rc;
4067}
4068
drhd9e5c4f2010-05-12 18:01:39 +00004069
4070/*
drhd91c68f2010-05-14 14:52:25 +00004071** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004072**
4073** This is not a VFS shared-memory method; it is a utility function called
4074** by VFS shared-memory methods.
4075*/
drhd91c68f2010-05-14 14:52:25 +00004076static void unixShmPurge(unixFile *pFd){
4077 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004078 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004079 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004080 int i;
drhd91c68f2010-05-14 14:52:25 +00004081 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004082 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004083 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004084 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004085 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004086 }else{
4087 sqlite3_free(p->apRegion[i]);
4088 }
dan13a3cb82010-06-11 19:04:21 +00004089 }
dan18801912010-06-14 14:07:50 +00004090 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004091 if( p->h>=0 ){
4092 robust_close(pFd, p->h, __LINE__);
4093 p->h = -1;
4094 }
drhd91c68f2010-05-14 14:52:25 +00004095 p->pInode->pShmNode = 0;
4096 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004097 }
4098}
4099
4100/*
danda9fe0c2010-07-13 18:44:03 +00004101** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004102** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004103**
drh7234c6d2010-06-19 15:10:09 +00004104** The file used to implement shared-memory is in the same directory
4105** as the open database file and has the same name as the open database
4106** file with the "-shm" suffix added. For example, if the database file
4107** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004108** for shared memory will be called "/home/user1/config.db-shm".
4109**
4110** Another approach to is to use files in /dev/shm or /dev/tmp or an
4111** some other tmpfs mount. But if a file in a different directory
4112** from the database file is used, then differing access permissions
4113** or a chroot() might cause two different processes on the same
4114** database to end up using different files for shared memory -
4115** meaning that their memory would not really be shared - resulting
4116** in database corruption. Nevertheless, this tmpfs file usage
4117** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4118** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4119** option results in an incompatible build of SQLite; builds of SQLite
4120** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4121** same database file at the same time, database corruption will likely
4122** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4123** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004124**
4125** When opening a new shared-memory file, if no other instances of that
4126** file are currently open, in this process or in other processes, then
4127** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004128**
4129** If the original database file (pDbFd) is using the "unix-excl" VFS
4130** that means that an exclusive lock is held on the database file and
4131** that no other processes are able to read or write the database. In
4132** that case, we do not really need shared memory. No shared memory
4133** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004134*/
danda9fe0c2010-07-13 18:44:03 +00004135static int unixOpenSharedMemory(unixFile *pDbFd){
4136 struct unixShm *p = 0; /* The connection to be opened */
4137 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4138 int rc; /* Result code */
4139 unixInodeInfo *pInode; /* The inode of fd */
4140 char *zShmFilename; /* Name of the file used for SHM */
4141 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004142
danda9fe0c2010-07-13 18:44:03 +00004143 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004144 p = sqlite3_malloc( sizeof(*p) );
4145 if( p==0 ) return SQLITE_NOMEM;
4146 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004147 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004148
danda9fe0c2010-07-13 18:44:03 +00004149 /* Check to see if a unixShmNode object already exists. Reuse an existing
4150 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004151 */
4152 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004153 pInode = pDbFd->pInode;
4154 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004155 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004156 struct stat sStat; /* fstat() info for database file */
4157
4158 /* Call fstat() to figure out the permissions on the database file. If
4159 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004160 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004161 */
drh3cb93392011-03-12 18:10:44 +00004162 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004163 rc = SQLITE_IOERR_FSTAT;
4164 goto shm_open_err;
4165 }
4166
drha4ced192010-07-15 18:32:40 +00004167#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004168 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004169#else
drh52bcde02012-01-03 14:50:45 +00004170 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004171#endif
drh7234c6d2010-06-19 15:10:09 +00004172 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004173 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004174 rc = SQLITE_NOMEM;
4175 goto shm_open_err;
4176 }
drh9cb5a0d2012-01-05 21:19:54 +00004177 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004178 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004179#ifdef SQLITE_SHM_DIRECTORY
4180 sqlite3_snprintf(nShmFilename, zShmFilename,
4181 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4182 (u32)sStat.st_ino, (u32)sStat.st_dev);
4183#else
drh7234c6d2010-06-19 15:10:09 +00004184 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004185 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004186#endif
drhd91c68f2010-05-14 14:52:25 +00004187 pShmNode->h = -1;
4188 pDbFd->pInode->pShmNode = pShmNode;
4189 pShmNode->pInode = pDbFd->pInode;
4190 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4191 if( pShmNode->mutex==0 ){
4192 rc = SQLITE_NOMEM;
4193 goto shm_open_err;
4194 }
drhd9e5c4f2010-05-12 18:01:39 +00004195
drh3cb93392011-03-12 18:10:44 +00004196 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004197 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004198 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004199 openFlags = O_RDONLY;
4200 pShmNode->isReadonly = 1;
4201 }
4202 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004203 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004204 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4205 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004206 }
drhac7c3ac2012-02-11 19:23:48 +00004207
4208 /* If this process is running as root, make sure that the SHM file
4209 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004210 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004211 */
drhed466822012-05-31 13:10:49 +00004212 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004213
4214 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004215 ** If not, truncate the file to zero length.
4216 */
4217 rc = SQLITE_OK;
4218 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4219 if( robust_ftruncate(pShmNode->h, 0) ){
4220 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004221 }
4222 }
drh66dfec8b2011-06-01 20:01:49 +00004223 if( rc==SQLITE_OK ){
4224 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4225 }
4226 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004227 }
drhd9e5c4f2010-05-12 18:01:39 +00004228 }
4229
drhd91c68f2010-05-14 14:52:25 +00004230 /* Make the new connection a child of the unixShmNode */
4231 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004232#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004233 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004234#endif
drhd91c68f2010-05-14 14:52:25 +00004235 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004236 pDbFd->pShm = p;
4237 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004238
4239 /* The reference count on pShmNode has already been incremented under
4240 ** the cover of the unixEnterMutex() mutex and the pointer from the
4241 ** new (struct unixShm) object to the pShmNode has been set. All that is
4242 ** left to do is to link the new object into the linked list starting
4243 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4244 ** mutex.
4245 */
4246 sqlite3_mutex_enter(pShmNode->mutex);
4247 p->pNext = pShmNode->pFirst;
4248 pShmNode->pFirst = p;
4249 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004250 return SQLITE_OK;
4251
4252 /* Jump here on any error */
4253shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004254 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004255 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004256 unixLeaveMutex();
4257 return rc;
4258}
4259
4260/*
danda9fe0c2010-07-13 18:44:03 +00004261** This function is called to obtain a pointer to region iRegion of the
4262** shared-memory associated with the database file fd. Shared-memory regions
4263** are numbered starting from zero. Each shared-memory region is szRegion
4264** bytes in size.
4265**
4266** If an error occurs, an error code is returned and *pp is set to NULL.
4267**
4268** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4269** region has not been allocated (by any client, including one running in a
4270** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4271** bExtend is non-zero and the requested shared-memory region has not yet
4272** been allocated, it is allocated by this function.
4273**
4274** If the shared-memory region has already been allocated or is allocated by
4275** this call as described above, then it is mapped into this processes
4276** address space (if it is not already), *pp is set to point to the mapped
4277** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004278*/
danda9fe0c2010-07-13 18:44:03 +00004279static int unixShmMap(
4280 sqlite3_file *fd, /* Handle open on database file */
4281 int iRegion, /* Region to retrieve */
4282 int szRegion, /* Size of regions */
4283 int bExtend, /* True to extend file if necessary */
4284 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004285){
danda9fe0c2010-07-13 18:44:03 +00004286 unixFile *pDbFd = (unixFile*)fd;
4287 unixShm *p;
4288 unixShmNode *pShmNode;
4289 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004290
danda9fe0c2010-07-13 18:44:03 +00004291 /* If the shared-memory file has not yet been opened, open it now. */
4292 if( pDbFd->pShm==0 ){
4293 rc = unixOpenSharedMemory(pDbFd);
4294 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004295 }
drhd9e5c4f2010-05-12 18:01:39 +00004296
danda9fe0c2010-07-13 18:44:03 +00004297 p = pDbFd->pShm;
4298 pShmNode = p->pShmNode;
4299 sqlite3_mutex_enter(pShmNode->mutex);
4300 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004301 assert( pShmNode->pInode==pDbFd->pInode );
4302 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4303 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004304
4305 if( pShmNode->nRegion<=iRegion ){
4306 char **apNew; /* New apRegion[] array */
4307 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4308 struct stat sStat; /* Used by fstat() */
4309
4310 pShmNode->szRegion = szRegion;
4311
drh3cb93392011-03-12 18:10:44 +00004312 if( pShmNode->h>=0 ){
4313 /* The requested region is not mapped into this processes address space.
4314 ** Check to see if it has been allocated (i.e. if the wal-index file is
4315 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004316 */
drh3cb93392011-03-12 18:10:44 +00004317 if( osFstat(pShmNode->h, &sStat) ){
4318 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004319 goto shmpage_out;
4320 }
drh3cb93392011-03-12 18:10:44 +00004321
4322 if( sStat.st_size<nByte ){
4323 /* The requested memory region does not exist. If bExtend is set to
4324 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4325 **
4326 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4327 ** the requested memory region.
4328 */
4329 if( !bExtend ) goto shmpage_out;
drh0fbb50e2012-11-13 10:54:12 +00004330#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
4331 if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
4332 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
4333 pShmNode->zFilename);
4334 goto shmpage_out;
4335 }
4336#else
drh3cb93392011-03-12 18:10:44 +00004337 if( robust_ftruncate(pShmNode->h, nByte) ){
4338 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4339 pShmNode->zFilename);
4340 goto shmpage_out;
4341 }
drh0fbb50e2012-11-13 10:54:12 +00004342#endif
drh3cb93392011-03-12 18:10:44 +00004343 }
danda9fe0c2010-07-13 18:44:03 +00004344 }
4345
4346 /* Map the requested memory region into this processes address space. */
4347 apNew = (char **)sqlite3_realloc(
4348 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4349 );
4350 if( !apNew ){
4351 rc = SQLITE_IOERR_NOMEM;
4352 goto shmpage_out;
4353 }
4354 pShmNode->apRegion = apNew;
4355 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004356 void *pMem;
4357 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004358 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004359 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004360 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004361 );
4362 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004363 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004364 goto shmpage_out;
4365 }
4366 }else{
4367 pMem = sqlite3_malloc(szRegion);
4368 if( pMem==0 ){
4369 rc = SQLITE_NOMEM;
4370 goto shmpage_out;
4371 }
4372 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004373 }
4374 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4375 pShmNode->nRegion++;
4376 }
4377 }
4378
4379shmpage_out:
4380 if( pShmNode->nRegion>iRegion ){
4381 *pp = pShmNode->apRegion[iRegion];
4382 }else{
4383 *pp = 0;
4384 }
drh66dfec8b2011-06-01 20:01:49 +00004385 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004386 sqlite3_mutex_leave(pShmNode->mutex);
4387 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004388}
4389
4390/*
drhd9e5c4f2010-05-12 18:01:39 +00004391** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004392**
4393** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4394** different here than in posix. In xShmLock(), one can go from unlocked
4395** to shared and back or from unlocked to exclusive and back. But one may
4396** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004397*/
4398static int unixShmLock(
4399 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004400 int ofst, /* First lock to acquire or release */
4401 int n, /* Number of locks to acquire or release */
4402 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004403){
drh73b64e42010-05-30 19:55:15 +00004404 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4405 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4406 unixShm *pX; /* For looping over all siblings */
4407 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4408 int rc = SQLITE_OK; /* Result code */
4409 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004410
drhd91c68f2010-05-14 14:52:25 +00004411 assert( pShmNode==pDbFd->pInode->pShmNode );
4412 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004413 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004414 assert( n>=1 );
4415 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4416 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4417 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4418 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4419 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004420 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4421 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004422
drhc99597c2010-05-31 01:41:15 +00004423 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004424 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004425 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004426 if( flags & SQLITE_SHM_UNLOCK ){
4427 u16 allMask = 0; /* Mask of locks held by siblings */
4428
4429 /* See if any siblings hold this same lock */
4430 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4431 if( pX==p ) continue;
4432 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4433 allMask |= pX->sharedMask;
4434 }
4435
4436 /* Unlock the system-level locks */
4437 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004438 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004439 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004440 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004441 }
drh73b64e42010-05-30 19:55:15 +00004442
4443 /* Undo the local locks */
4444 if( rc==SQLITE_OK ){
4445 p->exclMask &= ~mask;
4446 p->sharedMask &= ~mask;
4447 }
4448 }else if( flags & SQLITE_SHM_SHARED ){
4449 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4450
4451 /* Find out which shared locks are already held by sibling connections.
4452 ** If any sibling already holds an exclusive lock, go ahead and return
4453 ** SQLITE_BUSY.
4454 */
4455 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004456 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004457 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004458 break;
4459 }
4460 allShared |= pX->sharedMask;
4461 }
4462
4463 /* Get shared locks at the system level, if necessary */
4464 if( rc==SQLITE_OK ){
4465 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004466 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004467 }else{
drh73b64e42010-05-30 19:55:15 +00004468 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004469 }
drhd9e5c4f2010-05-12 18:01:39 +00004470 }
drh73b64e42010-05-30 19:55:15 +00004471
4472 /* Get the local shared locks */
4473 if( rc==SQLITE_OK ){
4474 p->sharedMask |= mask;
4475 }
4476 }else{
4477 /* Make sure no sibling connections hold locks that will block this
4478 ** lock. If any do, return SQLITE_BUSY right away.
4479 */
4480 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004481 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4482 rc = SQLITE_BUSY;
4483 break;
4484 }
4485 }
4486
4487 /* Get the exclusive locks at the system level. Then if successful
4488 ** also mark the local connection as being locked.
4489 */
4490 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004491 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004492 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004493 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004494 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004495 }
drhd9e5c4f2010-05-12 18:01:39 +00004496 }
4497 }
drhd91c68f2010-05-14 14:52:25 +00004498 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004499 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4500 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004501 return rc;
4502}
4503
drh286a2882010-05-20 23:51:06 +00004504/*
4505** Implement a memory barrier or memory fence on shared memory.
4506**
4507** All loads and stores begun before the barrier must complete before
4508** any load or store begun after the barrier.
4509*/
4510static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004511 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004512){
drhff828942010-06-26 21:34:06 +00004513 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004514 unixEnterMutex();
4515 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004516}
4517
dan18801912010-06-14 14:07:50 +00004518/*
danda9fe0c2010-07-13 18:44:03 +00004519** Close a connection to shared-memory. Delete the underlying
4520** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004521**
4522** If there is no shared memory associated with the connection then this
4523** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004524*/
danda9fe0c2010-07-13 18:44:03 +00004525static int unixShmUnmap(
4526 sqlite3_file *fd, /* The underlying database file */
4527 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004528){
danda9fe0c2010-07-13 18:44:03 +00004529 unixShm *p; /* The connection to be closed */
4530 unixShmNode *pShmNode; /* The underlying shared-memory file */
4531 unixShm **pp; /* For looping over sibling connections */
4532 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004533
danda9fe0c2010-07-13 18:44:03 +00004534 pDbFd = (unixFile*)fd;
4535 p = pDbFd->pShm;
4536 if( p==0 ) return SQLITE_OK;
4537 pShmNode = p->pShmNode;
4538
4539 assert( pShmNode==pDbFd->pInode->pShmNode );
4540 assert( pShmNode->pInode==pDbFd->pInode );
4541
4542 /* Remove connection p from the set of connections associated
4543 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004544 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004545 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4546 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004547
danda9fe0c2010-07-13 18:44:03 +00004548 /* Free the connection p */
4549 sqlite3_free(p);
4550 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004551 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004552
4553 /* If pShmNode->nRef has reached 0, then close the underlying
4554 ** shared-memory file, too */
4555 unixEnterMutex();
4556 assert( pShmNode->nRef>0 );
4557 pShmNode->nRef--;
4558 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004559 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004560 unixShmPurge(pDbFd);
4561 }
4562 unixLeaveMutex();
4563
4564 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004565}
drh286a2882010-05-20 23:51:06 +00004566
danda9fe0c2010-07-13 18:44:03 +00004567
drhd9e5c4f2010-05-12 18:01:39 +00004568#else
drh6b017cc2010-06-14 18:01:46 +00004569# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004570# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004571# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004572# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004573#endif /* #ifndef SQLITE_OMIT_WAL */
4574
drh734c9862008-11-28 15:37:20 +00004575/*
danaef49d72013-03-25 16:28:54 +00004576** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004577*/
danf23da962013-03-23 21:00:41 +00004578static void unixUnmapfile(unixFile *pFd){
4579 assert( pFd->nFetchOut==0 );
drh9b4c59f2013-04-15 17:03:42 +00004580#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004581 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004582 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004583 pFd->pMapRegion = 0;
4584 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004585 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004586 }
drh6e0b6d52013-04-09 16:19:20 +00004587#endif
danf23da962013-03-23 21:00:41 +00004588}
dan5d8a1372013-03-19 19:28:06 +00004589
drh9b4c59f2013-04-15 17:03:42 +00004590#if SQLITE_MAX_MMAP_SIZE>0
danaef49d72013-03-25 16:28:54 +00004591/*
dane6ecd662013-04-01 17:56:59 +00004592** Return the system page size.
4593*/
4594static int unixGetPagesize(void){
4595#if HAVE_MREMAP
4596 return 512;
drh85830a72013-04-03 00:42:01 +00004597#elif defined(_BSD_SOURCE)
dane6ecd662013-04-01 17:56:59 +00004598 return getpagesize();
4599#else
4600 return (int)sysconf(_SC_PAGESIZE);
4601#endif
4602}
drh9b4c59f2013-04-15 17:03:42 +00004603#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dane6ecd662013-04-01 17:56:59 +00004604
drh9b4c59f2013-04-15 17:03:42 +00004605#if SQLITE_MAX_MMAP_SIZE>0
dane6ecd662013-04-01 17:56:59 +00004606/*
4607** Attempt to set the size of the memory mapping maintained by file
4608** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4609**
4610** If successful, this function sets the following variables:
4611**
4612** unixFile.pMapRegion
4613** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004614** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004615**
4616** If unsuccessful, an error message is logged via sqlite3_log() and
4617** the three variables above are zeroed. In this case SQLite should
4618** continue accessing the database using the xRead() and xWrite()
4619** methods.
4620*/
4621static void unixRemapfile(
4622 unixFile *pFd, /* File descriptor object */
4623 i64 nNew /* Required mapping size */
4624){
dan4ff7bc42013-04-02 12:04:09 +00004625 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004626 int h = pFd->h; /* File descriptor open on db file */
4627 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004628 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004629 u8 *pNew = 0; /* Location of new mapping */
4630 int flags = PROT_READ; /* Flags to pass to mmap() */
4631
4632 assert( pFd->nFetchOut==0 );
4633 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004634 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004635 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004636 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004637 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004638
4639 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4640
4641 if( pOrig ){
4642 const int szSyspage = unixGetPagesize();
4643 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4644 u8 *pReq = &pOrig[nReuse];
4645
4646 /* Unmap any pages of the existing mapping that cannot be reused. */
4647 if( nReuse!=nOrig ){
4648 osMunmap(pReq, nOrig-nReuse);
4649 }
4650
4651#if HAVE_MREMAP
4652 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004653 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004654#else
4655 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4656 if( pNew!=MAP_FAILED ){
4657 if( pNew!=pReq ){
4658 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004659 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004660 }else{
4661 pNew = pOrig;
4662 }
4663 }
4664#endif
4665
dan48ccef82013-04-02 20:55:01 +00004666 /* The attempt to extend the existing mapping failed. Free it. */
4667 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004668 osMunmap(pOrig, nReuse);
4669 }
4670 }
4671
4672 /* If pNew is still NULL, try to create an entirely new mapping. */
4673 if( pNew==0 ){
4674 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004675 }
4676
dan4ff7bc42013-04-02 12:04:09 +00004677 if( pNew==MAP_FAILED ){
4678 pNew = 0;
4679 nNew = 0;
4680 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4681
4682 /* If the mmap() above failed, assume that all subsequent mmap() calls
4683 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4684 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004685 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004686 }
dane6ecd662013-04-01 17:56:59 +00004687 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004688 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004689}
drh6e0b6d52013-04-09 16:19:20 +00004690#endif
dane6ecd662013-04-01 17:56:59 +00004691
4692/*
danaef49d72013-03-25 16:28:54 +00004693** Memory map or remap the file opened by file-descriptor pFd (if the file
4694** is already mapped, the existing mapping is replaced by the new). Or, if
4695** there already exists a mapping for this file, and there are still
4696** outstanding xFetch() references to it, this function is a no-op.
4697**
4698** If parameter nByte is non-negative, then it is the requested size of
4699** the mapping to create. Otherwise, if nByte is less than zero, then the
4700** requested size is the size of the file on disk. The actual size of the
4701** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004702** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004703**
4704** SQLITE_OK is returned if no error occurs (even if the mapping is not
4705** recreated as a result of outstanding references) or an SQLite error
4706** code otherwise.
4707*/
danf23da962013-03-23 21:00:41 +00004708static int unixMapfile(unixFile *pFd, i64 nByte){
drh9b4c59f2013-04-15 17:03:42 +00004709#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004710 i64 nMap = nByte;
4711 int rc;
daneb97b292013-03-20 14:26:59 +00004712
danf23da962013-03-23 21:00:41 +00004713 assert( nMap>=0 || pFd->nFetchOut==0 );
4714 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4715
4716 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004717 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004718 rc = osFstat(pFd->h, &statbuf);
4719 if( rc!=SQLITE_OK ){
4720 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004721 }
danf23da962013-03-23 21:00:41 +00004722 nMap = statbuf.st_size;
4723 }
drh9b4c59f2013-04-15 17:03:42 +00004724 if( nMap>pFd->mmapSizeMax ){
4725 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004726 }
4727
danf23da962013-03-23 21:00:41 +00004728 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004729 if( nMap>0 ){
4730 unixRemapfile(pFd, nMap);
4731 }else{
danb7e3a322013-03-25 20:30:13 +00004732 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004733 }
4734 }
drh6e0b6d52013-04-09 16:19:20 +00004735#endif
dan5d8a1372013-03-19 19:28:06 +00004736
danf23da962013-03-23 21:00:41 +00004737 return SQLITE_OK;
4738}
4739
danaef49d72013-03-25 16:28:54 +00004740/*
4741** If possible, return a pointer to a mapping of file fd starting at offset
4742** iOff. The mapping must be valid for at least nAmt bytes.
4743**
4744** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4745** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4746** Finally, if an error does occur, return an SQLite error code. The final
4747** value of *pp is undefined in this case.
4748**
4749** If this function does return a pointer, the caller must eventually
4750** release the reference by calling unixUnfetch().
4751*/
danf23da962013-03-23 21:00:41 +00004752static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004753#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004754 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004755#endif
danf23da962013-03-23 21:00:41 +00004756 *pp = 0;
4757
drh9b4c59f2013-04-15 17:03:42 +00004758#if SQLITE_MAX_MMAP_SIZE>0
4759 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004760 if( pFd->pMapRegion==0 ){
4761 int rc = unixMapfile(pFd, -1);
4762 if( rc!=SQLITE_OK ) return rc;
4763 }
4764 if( pFd->mmapSize >= iOff+nAmt ){
4765 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4766 pFd->nFetchOut++;
4767 }
4768 }
drh6e0b6d52013-04-09 16:19:20 +00004769#endif
danf23da962013-03-23 21:00:41 +00004770 return SQLITE_OK;
4771}
4772
danaef49d72013-03-25 16:28:54 +00004773/*
dandf737fe2013-03-25 17:00:24 +00004774** If the third argument is non-NULL, then this function releases a
4775** reference obtained by an earlier call to unixFetch(). The second
4776** argument passed to this function must be the same as the corresponding
4777** argument that was passed to the unixFetch() invocation.
4778**
4779** Or, if the third argument is NULL, then this function is being called
4780** to inform the VFS layer that, according to POSIX, any existing mapping
4781** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004782*/
dandf737fe2013-03-25 17:00:24 +00004783static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
danf23da962013-03-23 21:00:41 +00004784 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4785
danaef49d72013-03-25 16:28:54 +00004786 /* If p==0 (unmap the entire file) then there must be no outstanding
4787 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4788 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004789 assert( (p==0)==(pFd->nFetchOut==0) );
4790
dandf737fe2013-03-25 17:00:24 +00004791 /* If p!=0, it must match the iOff value. */
4792 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4793
danf23da962013-03-23 21:00:41 +00004794 if( p ){
4795 pFd->nFetchOut--;
4796 }else{
4797 unixUnmapfile(pFd);
4798 }
4799
4800 assert( pFd->nFetchOut>=0 );
4801 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004802}
4803
4804/*
drh734c9862008-11-28 15:37:20 +00004805** Here ends the implementation of all sqlite3_file methods.
4806**
4807********************** End sqlite3_file Methods *******************************
4808******************************************************************************/
4809
4810/*
drh6b9d6dd2008-12-03 19:34:47 +00004811** This division contains definitions of sqlite3_io_methods objects that
4812** implement various file locking strategies. It also contains definitions
4813** of "finder" functions. A finder-function is used to locate the appropriate
4814** sqlite3_io_methods object for a particular database file. The pAppData
4815** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4816** the correct finder-function for that VFS.
4817**
4818** Most finder functions return a pointer to a fixed sqlite3_io_methods
4819** object. The only interesting finder-function is autolockIoFinder, which
4820** looks at the filesystem type and tries to guess the best locking
4821** strategy from that.
4822**
drh1875f7a2008-12-08 18:19:17 +00004823** For finder-funtion F, two objects are created:
4824**
4825** (1) The real finder-function named "FImpt()".
4826**
dane946c392009-08-22 11:39:46 +00004827** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004828**
4829**
4830** A pointer to the F pointer is used as the pAppData value for VFS
4831** objects. We have to do this instead of letting pAppData point
4832** directly at the finder-function since C90 rules prevent a void*
4833** from be cast into a function pointer.
4834**
drh6b9d6dd2008-12-03 19:34:47 +00004835**
drh7708e972008-11-29 00:56:52 +00004836** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004837**
drh7708e972008-11-29 00:56:52 +00004838** * A constant sqlite3_io_methods object call METHOD that has locking
4839** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4840**
4841** * An I/O method finder function called FINDER that returns a pointer
4842** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004843*/
drhd9e5c4f2010-05-12 18:01:39 +00004844#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004845static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004846 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004847 CLOSE, /* xClose */ \
4848 unixRead, /* xRead */ \
4849 unixWrite, /* xWrite */ \
4850 unixTruncate, /* xTruncate */ \
4851 unixSync, /* xSync */ \
4852 unixFileSize, /* xFileSize */ \
4853 LOCK, /* xLock */ \
4854 UNLOCK, /* xUnlock */ \
4855 CKLOCK, /* xCheckReservedLock */ \
4856 unixFileControl, /* xFileControl */ \
4857 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004858 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004859 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004860 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004861 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004862 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004863 unixFetch, /* xFetch */ \
4864 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004865}; \
drh0c2694b2009-09-03 16:23:44 +00004866static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4867 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004868 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004869} \
drh0c2694b2009-09-03 16:23:44 +00004870static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004871 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004872
4873/*
4874** Here are all of the sqlite3_io_methods objects for each of the
4875** locking strategies. Functions that return pointers to these methods
4876** are also created.
4877*/
4878IOMETHODS(
4879 posixIoFinder, /* Finder function name */
4880 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004881 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004882 unixClose, /* xClose method */
4883 unixLock, /* xLock method */
4884 unixUnlock, /* xUnlock method */
4885 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004886)
drh7708e972008-11-29 00:56:52 +00004887IOMETHODS(
4888 nolockIoFinder, /* Finder function name */
4889 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004890 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004891 nolockClose, /* xClose method */
4892 nolockLock, /* xLock method */
4893 nolockUnlock, /* xUnlock method */
4894 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004895)
drh7708e972008-11-29 00:56:52 +00004896IOMETHODS(
4897 dotlockIoFinder, /* Finder function name */
4898 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004899 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004900 dotlockClose, /* xClose method */
4901 dotlockLock, /* xLock method */
4902 dotlockUnlock, /* xUnlock method */
4903 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004904)
drh7708e972008-11-29 00:56:52 +00004905
chw78a13182009-04-07 05:35:03 +00004906#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004907IOMETHODS(
4908 flockIoFinder, /* Finder function name */
4909 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004910 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004911 flockClose, /* xClose method */
4912 flockLock, /* xLock method */
4913 flockUnlock, /* xUnlock method */
4914 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004915)
drh7708e972008-11-29 00:56:52 +00004916#endif
4917
drh6c7d5c52008-11-21 20:32:33 +00004918#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004919IOMETHODS(
4920 semIoFinder, /* Finder function name */
4921 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004922 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004923 semClose, /* xClose method */
4924 semLock, /* xLock method */
4925 semUnlock, /* xUnlock method */
4926 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004927)
aswiftaebf4132008-11-21 00:10:35 +00004928#endif
drh7708e972008-11-29 00:56:52 +00004929
drhd2cb50b2009-01-09 21:41:17 +00004930#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004931IOMETHODS(
4932 afpIoFinder, /* Finder function name */
4933 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004934 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004935 afpClose, /* xClose method */
4936 afpLock, /* xLock method */
4937 afpUnlock, /* xUnlock method */
4938 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004939)
drh715ff302008-12-03 22:32:44 +00004940#endif
4941
4942/*
4943** The proxy locking method is a "super-method" in the sense that it
4944** opens secondary file descriptors for the conch and lock files and
4945** it uses proxy, dot-file, AFP, and flock() locking methods on those
4946** secondary files. For this reason, the division that implements
4947** proxy locking is located much further down in the file. But we need
4948** to go ahead and define the sqlite3_io_methods and finder function
4949** for proxy locking here. So we forward declare the I/O methods.
4950*/
drhd2cb50b2009-01-09 21:41:17 +00004951#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004952static int proxyClose(sqlite3_file*);
4953static int proxyLock(sqlite3_file*, int);
4954static int proxyUnlock(sqlite3_file*, int);
4955static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004956IOMETHODS(
4957 proxyIoFinder, /* Finder function name */
4958 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004959 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004960 proxyClose, /* xClose method */
4961 proxyLock, /* xLock method */
4962 proxyUnlock, /* xUnlock method */
4963 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004964)
aswiftaebf4132008-11-21 00:10:35 +00004965#endif
drh7708e972008-11-29 00:56:52 +00004966
drh7ed97b92010-01-20 13:07:21 +00004967/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4968#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4969IOMETHODS(
4970 nfsIoFinder, /* Finder function name */
4971 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004972 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004973 unixClose, /* xClose method */
4974 unixLock, /* xLock method */
4975 nfsUnlock, /* xUnlock method */
4976 unixCheckReservedLock /* xCheckReservedLock method */
4977)
4978#endif
drh7708e972008-11-29 00:56:52 +00004979
drhd2cb50b2009-01-09 21:41:17 +00004980#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004981/*
drh6b9d6dd2008-12-03 19:34:47 +00004982** This "finder" function attempts to determine the best locking strategy
4983** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004984** object that implements that strategy.
4985**
4986** This is for MacOSX only.
4987*/
drh1875f7a2008-12-08 18:19:17 +00004988static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004989 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004990 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004991){
4992 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004993 const char *zFilesystem; /* Filesystem type name */
4994 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004995 } aMap[] = {
4996 { "hfs", &posixIoMethods },
4997 { "ufs", &posixIoMethods },
4998 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004999 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005000 { "webdav", &nolockIoMethods },
5001 { 0, 0 }
5002 };
5003 int i;
5004 struct statfs fsInfo;
5005 struct flock lockInfo;
5006
5007 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005008 /* If filePath==NULL that means we are dealing with a transient file
5009 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005010 return &nolockIoMethods;
5011 }
5012 if( statfs(filePath, &fsInfo) != -1 ){
5013 if( fsInfo.f_flags & MNT_RDONLY ){
5014 return &nolockIoMethods;
5015 }
5016 for(i=0; aMap[i].zFilesystem; i++){
5017 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5018 return aMap[i].pMethods;
5019 }
5020 }
5021 }
5022
5023 /* Default case. Handles, amongst others, "nfs".
5024 ** Test byte-range lock using fcntl(). If the call succeeds,
5025 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005026 */
drh7708e972008-11-29 00:56:52 +00005027 lockInfo.l_len = 1;
5028 lockInfo.l_start = 0;
5029 lockInfo.l_whence = SEEK_SET;
5030 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005031 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005032 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5033 return &nfsIoMethods;
5034 } else {
5035 return &posixIoMethods;
5036 }
drh7708e972008-11-29 00:56:52 +00005037 }else{
5038 return &dotlockIoMethods;
5039 }
5040}
drh0c2694b2009-09-03 16:23:44 +00005041static const sqlite3_io_methods
5042 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005043
drhd2cb50b2009-01-09 21:41:17 +00005044#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005045
chw78a13182009-04-07 05:35:03 +00005046#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5047/*
5048** This "finder" function attempts to determine the best locking strategy
5049** for the database file "filePath". It then returns the sqlite3_io_methods
5050** object that implements that strategy.
5051**
5052** This is for VXWorks only.
5053*/
5054static const sqlite3_io_methods *autolockIoFinderImpl(
5055 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005056 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005057){
5058 struct flock lockInfo;
5059
5060 if( !filePath ){
5061 /* If filePath==NULL that means we are dealing with a transient file
5062 ** that does not need to be locked. */
5063 return &nolockIoMethods;
5064 }
5065
5066 /* Test if fcntl() is supported and use POSIX style locks.
5067 ** Otherwise fall back to the named semaphore method.
5068 */
5069 lockInfo.l_len = 1;
5070 lockInfo.l_start = 0;
5071 lockInfo.l_whence = SEEK_SET;
5072 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005073 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005074 return &posixIoMethods;
5075 }else{
5076 return &semIoMethods;
5077 }
5078}
drh0c2694b2009-09-03 16:23:44 +00005079static const sqlite3_io_methods
5080 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005081
5082#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5083
drh7708e972008-11-29 00:56:52 +00005084/*
5085** An abstract type for a pointer to a IO method finder function:
5086*/
drh0c2694b2009-09-03 16:23:44 +00005087typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005088
aswiftaebf4132008-11-21 00:10:35 +00005089
drh734c9862008-11-28 15:37:20 +00005090/****************************************************************************
5091**************************** sqlite3_vfs methods ****************************
5092**
5093** This division contains the implementation of methods on the
5094** sqlite3_vfs object.
5095*/
5096
danielk1977a3d4c882007-03-23 10:08:38 +00005097/*
danielk1977e339d652008-06-28 11:23:00 +00005098** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005099*/
5100static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005101 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005102 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005103 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005104 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005105 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005106){
drh7708e972008-11-29 00:56:52 +00005107 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005108 unixFile *pNew = (unixFile *)pId;
5109 int rc = SQLITE_OK;
5110
drh8af6c222010-05-14 12:43:01 +00005111 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005112
dan00157392010-10-05 11:33:15 +00005113 /* Usually the path zFilename should not be a relative pathname. The
5114 ** exception is when opening the proxy "conch" file in builds that
5115 ** include the special Apple locking styles.
5116 */
dan00157392010-10-05 11:33:15 +00005117#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005118 assert( zFilename==0 || zFilename[0]=='/'
5119 || pVfs->pAppData==(void*)&autolockIoFinder );
5120#else
5121 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005122#endif
dan00157392010-10-05 11:33:15 +00005123
drhb07028f2011-10-14 21:49:18 +00005124 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005125 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005126
drh308c2a52010-05-14 11:30:18 +00005127 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005128 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005129 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005130 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005131 pNew->ctrlFlags = (u8)ctrlFlags;
drh9b4c59f2013-04-15 17:03:42 +00005132 pNew->mmapSizeMax = sqlite3GlobalConfig.mxMmap;
drhc02a43a2012-01-10 23:18:38 +00005133 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5134 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005135 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005136 }
drh503a6862013-03-01 01:07:17 +00005137 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005138 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005139 }
drh339eb0b2008-03-07 15:34:11 +00005140
drh6c7d5c52008-11-21 20:32:33 +00005141#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005142 pNew->pId = vxworksFindFileId(zFilename);
5143 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005144 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005145 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005146 }
5147#endif
5148
drhc02a43a2012-01-10 23:18:38 +00005149 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005150 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005151 }else{
drh0c2694b2009-09-03 16:23:44 +00005152 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005153#if SQLITE_ENABLE_LOCKING_STYLE
5154 /* Cache zFilename in the locking context (AFP and dotlock override) for
5155 ** proxyLock activation is possible (remote proxy is based on db name)
5156 ** zFilename remains valid until file is closed, to support */
5157 pNew->lockingContext = (void*)zFilename;
5158#endif
drhda0e7682008-07-30 15:27:54 +00005159 }
danielk1977e339d652008-06-28 11:23:00 +00005160
drh7ed97b92010-01-20 13:07:21 +00005161 if( pLockingStyle == &posixIoMethods
5162#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5163 || pLockingStyle == &nfsIoMethods
5164#endif
5165 ){
drh7708e972008-11-29 00:56:52 +00005166 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005167 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005168 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005169 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005170 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005171 ** in two scenarios:
5172 **
5173 ** (a) A call to fstat() failed.
5174 ** (b) A malloc failed.
5175 **
5176 ** Scenario (b) may only occur if the process is holding no other
5177 ** file descriptors open on the same file. If there were other file
5178 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005179 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005180 ** handle h - as it is guaranteed that no posix locks will be released
5181 ** by doing so.
5182 **
5183 ** If scenario (a) caused the error then things are not so safe. The
5184 ** implicit assumption here is that if fstat() fails, things are in
5185 ** such bad shape that dropping a lock or two doesn't matter much.
5186 */
drh0e9365c2011-03-02 02:08:13 +00005187 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005188 h = -1;
5189 }
drh7708e972008-11-29 00:56:52 +00005190 unixLeaveMutex();
5191 }
danielk1977e339d652008-06-28 11:23:00 +00005192
drhd2cb50b2009-01-09 21:41:17 +00005193#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005194 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005195 /* AFP locking uses the file path so it needs to be included in
5196 ** the afpLockingContext.
5197 */
5198 afpLockingContext *pCtx;
5199 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5200 if( pCtx==0 ){
5201 rc = SQLITE_NOMEM;
5202 }else{
5203 /* NB: zFilename exists and remains valid until the file is closed
5204 ** according to requirement F11141. So we do not need to make a
5205 ** copy of the filename. */
5206 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005207 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005208 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005209 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005210 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005211 if( rc!=SQLITE_OK ){
5212 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005213 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005214 h = -1;
5215 }
drh7708e972008-11-29 00:56:52 +00005216 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005217 }
drh7708e972008-11-29 00:56:52 +00005218 }
5219#endif
danielk1977e339d652008-06-28 11:23:00 +00005220
drh7708e972008-11-29 00:56:52 +00005221 else if( pLockingStyle == &dotlockIoMethods ){
5222 /* Dotfile locking uses the file path so it needs to be included in
5223 ** the dotlockLockingContext
5224 */
5225 char *zLockFile;
5226 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005227 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005228 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005229 zLockFile = (char *)sqlite3_malloc(nFilename);
5230 if( zLockFile==0 ){
5231 rc = SQLITE_NOMEM;
5232 }else{
5233 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005234 }
drh7708e972008-11-29 00:56:52 +00005235 pNew->lockingContext = zLockFile;
5236 }
danielk1977e339d652008-06-28 11:23:00 +00005237
drh6c7d5c52008-11-21 20:32:33 +00005238#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005239 else if( pLockingStyle == &semIoMethods ){
5240 /* Named semaphore locking uses the file path so it needs to be
5241 ** included in the semLockingContext
5242 */
5243 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005244 rc = findInodeInfo(pNew, &pNew->pInode);
5245 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5246 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005247 int n;
drh2238dcc2009-08-27 17:56:20 +00005248 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005249 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005250 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005251 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005252 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5253 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005254 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005255 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005256 }
chw97185482008-11-17 08:05:31 +00005257 }
drh7708e972008-11-29 00:56:52 +00005258 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005259 }
drh7708e972008-11-29 00:56:52 +00005260#endif
aswift5b1a2562008-08-22 00:22:35 +00005261
5262 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005263#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005264 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005265 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005266 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005267 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00005268 isDelete = 0;
5269 }
drhc02a43a2012-01-10 23:18:38 +00005270 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005271#endif
danielk1977e339d652008-06-28 11:23:00 +00005272 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005273 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005274 }else{
drh7708e972008-11-29 00:56:52 +00005275 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005276 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005277 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005278 }
danielk1977e339d652008-06-28 11:23:00 +00005279 return rc;
drh054889e2005-11-30 03:20:31 +00005280}
drh9c06c952005-11-26 00:25:00 +00005281
danielk1977ad94b582007-08-20 06:44:22 +00005282/*
drh8b3cf822010-06-01 21:02:51 +00005283** Return the name of a directory in which to put temporary files.
5284** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005285*/
drh7234c6d2010-06-19 15:10:09 +00005286static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005287 static const char *azDirs[] = {
5288 0,
aswiftaebf4132008-11-21 00:10:35 +00005289 0,
danielk197717b90b52008-06-06 11:11:25 +00005290 "/var/tmp",
5291 "/usr/tmp",
5292 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005293 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005294 };
drh8b3cf822010-06-01 21:02:51 +00005295 unsigned int i;
5296 struct stat buf;
5297 const char *zDir = 0;
5298
5299 azDirs[0] = sqlite3_temp_directory;
5300 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005301 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005302 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005303 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005304 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005305 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005306 break;
5307 }
5308 return zDir;
5309}
5310
5311/*
5312** Create a temporary file name in zBuf. zBuf must be allocated
5313** by the calling process and must be big enough to hold at least
5314** pVfs->mxPathname bytes.
5315*/
5316static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005317 static const unsigned char zChars[] =
5318 "abcdefghijklmnopqrstuvwxyz"
5319 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5320 "0123456789";
drh41022642008-11-21 00:24:42 +00005321 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005322 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005323
5324 /* It's odd to simulate an io-error here, but really this is just
5325 ** using the io-error infrastructure to test that SQLite handles this
5326 ** function failing.
5327 */
5328 SimulateIOError( return SQLITE_IOERR );
5329
drh7234c6d2010-06-19 15:10:09 +00005330 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005331 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005332
5333 /* Check that the output buffer is large enough for the temporary file
5334 ** name. If it is not, return SQLITE_ERROR.
5335 */
drhc02a43a2012-01-10 23:18:38 +00005336 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005337 return SQLITE_ERROR;
5338 }
5339
5340 do{
drhc02a43a2012-01-10 23:18:38 +00005341 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005342 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005343 sqlite3_randomness(15, &zBuf[j]);
5344 for(i=0; i<15; i++, j++){
5345 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5346 }
5347 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005348 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005349 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005350 return SQLITE_OK;
5351}
5352
drhd2cb50b2009-01-09 21:41:17 +00005353#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005354/*
5355** Routine to transform a unixFile into a proxy-locking unixFile.
5356** Implementation in the proxy-lock division, but used by unixOpen()
5357** if SQLITE_PREFER_PROXY_LOCKING is defined.
5358*/
5359static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005360#endif
drhc66d5b62008-12-03 22:48:32 +00005361
dan08da86a2009-08-21 17:18:03 +00005362/*
5363** Search for an unused file descriptor that was opened on the database
5364** file (not a journal or master-journal file) identified by pathname
5365** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5366** argument to this function.
5367**
5368** Such a file descriptor may exist if a database connection was closed
5369** but the associated file descriptor could not be closed because some
5370** other file descriptor open on the same file is holding a file-lock.
5371** Refer to comments in the unixClose() function and the lengthy comment
5372** describing "Posix Advisory Locking" at the start of this file for
5373** further details. Also, ticket #4018.
5374**
5375** If a suitable file descriptor is found, then it is returned. If no
5376** such file descriptor is located, -1 is returned.
5377*/
dane946c392009-08-22 11:39:46 +00005378static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5379 UnixUnusedFd *pUnused = 0;
5380
5381 /* Do not search for an unused file descriptor on vxworks. Not because
5382 ** vxworks would not benefit from the change (it might, we're not sure),
5383 ** but because no way to test it is currently available. It is better
5384 ** not to risk breaking vxworks support for the sake of such an obscure
5385 ** feature. */
5386#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005387 struct stat sStat; /* Results of stat() call */
5388
5389 /* A stat() call may fail for various reasons. If this happens, it is
5390 ** almost certain that an open() call on the same path will also fail.
5391 ** For this reason, if an error occurs in the stat() call here, it is
5392 ** ignored and -1 is returned. The caller will try to open a new file
5393 ** descriptor on the same path, fail, and return an error to SQLite.
5394 **
5395 ** Even if a subsequent open() call does succeed, the consequences of
5396 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005397 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005398 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005399
5400 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005401 pInode = inodeList;
5402 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5403 || pInode->fileId.ino!=sStat.st_ino) ){
5404 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005405 }
drh8af6c222010-05-14 12:43:01 +00005406 if( pInode ){
dane946c392009-08-22 11:39:46 +00005407 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005408 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005409 pUnused = *pp;
5410 if( pUnused ){
5411 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005412 }
5413 }
5414 unixLeaveMutex();
5415 }
dane946c392009-08-22 11:39:46 +00005416#endif /* if !OS_VXWORKS */
5417 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005418}
danielk197717b90b52008-06-06 11:11:25 +00005419
5420/*
danddb0ac42010-07-14 14:48:58 +00005421** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005422** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005423** and a value suitable for passing as the third argument to open(2) is
5424** written to *pMode. If an IO error occurs, an SQLite error code is
5425** returned and the value of *pMode is not modified.
5426**
drh8c815d12012-02-13 20:16:37 +00005427** In most cases cases, this routine sets *pMode to 0, which will become
5428** an indication to robust_open() to create the file using
5429** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5430** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005431** this function queries the file-system for the permissions on the
5432** corresponding database file and sets *pMode to this value. Whenever
5433** possible, WAL and journal files are created using the same permissions
5434** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005435**
5436** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5437** original filename is unavailable. But 8_3_NAMES is only used for
5438** FAT filesystems and permissions do not matter there, so just use
5439** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005440*/
5441static int findCreateFileMode(
5442 const char *zPath, /* Path of file (possibly) being created */
5443 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005444 mode_t *pMode, /* OUT: Permissions to open file with */
5445 uid_t *pUid, /* OUT: uid to set on the file */
5446 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005447){
5448 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005449 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005450 *pUid = 0;
5451 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005452 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005453 char zDb[MAX_PATHNAME+1]; /* Database file path */
5454 int nDb; /* Number of valid bytes in zDb */
5455 struct stat sStat; /* Output of stat() on database file */
5456
dana0c989d2010-11-05 18:07:37 +00005457 /* zPath is a path to a WAL or journal file. The following block derives
5458 ** the path to the associated database file from zPath. This block handles
5459 ** the following naming conventions:
5460 **
5461 ** "<path to db>-journal"
5462 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005463 ** "<path to db>-journalNN"
5464 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005465 **
drhd337c5b2011-10-20 18:23:35 +00005466 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005467 ** used by the test_multiplex.c module.
5468 */
5469 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005470#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005471 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005472 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005473#else
5474 while( zPath[nDb]!='-' ){
5475 assert( nDb>0 );
5476 assert( zPath[nDb]!='\n' );
5477 nDb--;
5478 }
5479#endif
danddb0ac42010-07-14 14:48:58 +00005480 memcpy(zDb, zPath, nDb);
5481 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005482
drh58384f12011-07-28 00:14:45 +00005483 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005484 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005485 *pUid = sStat.st_uid;
5486 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005487 }else{
5488 rc = SQLITE_IOERR_FSTAT;
5489 }
5490 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5491 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005492 }
5493 return rc;
5494}
5495
5496/*
danielk1977ad94b582007-08-20 06:44:22 +00005497** Open the file zPath.
5498**
danielk1977b4b47412007-08-17 15:53:36 +00005499** Previously, the SQLite OS layer used three functions in place of this
5500** one:
5501**
5502** sqlite3OsOpenReadWrite();
5503** sqlite3OsOpenReadOnly();
5504** sqlite3OsOpenExclusive();
5505**
5506** These calls correspond to the following combinations of flags:
5507**
5508** ReadWrite() -> (READWRITE | CREATE)
5509** ReadOnly() -> (READONLY)
5510** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5511**
5512** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5513** true, the file was configured to be automatically deleted when the
5514** file handle closed. To achieve the same effect using this new
5515** interface, add the DELETEONCLOSE flag to those specified above for
5516** OpenExclusive().
5517*/
5518static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005519 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5520 const char *zPath, /* Pathname of file to be opened */
5521 sqlite3_file *pFile, /* The file descriptor to be filled in */
5522 int flags, /* Input flags to control the opening */
5523 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005524){
dan08da86a2009-08-21 17:18:03 +00005525 unixFile *p = (unixFile *)pFile;
5526 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005527 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005528 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005529 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005530 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005531 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005532
5533 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5534 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5535 int isCreate = (flags & SQLITE_OPEN_CREATE);
5536 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5537 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005538#if SQLITE_ENABLE_LOCKING_STYLE
5539 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5540#endif
drh3d4435b2011-08-26 20:55:50 +00005541#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5542 struct statfs fsInfo;
5543#endif
danielk1977b4b47412007-08-17 15:53:36 +00005544
danielk1977fee2d252007-08-18 10:59:19 +00005545 /* If creating a master or main-file journal, this function will open
5546 ** a file-descriptor on the directory too. The first time unixSync()
5547 ** is called the directory file descriptor will be fsync()ed and close()d.
5548 */
drh0059eae2011-08-08 23:48:40 +00005549 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005550 eType==SQLITE_OPEN_MASTER_JOURNAL
5551 || eType==SQLITE_OPEN_MAIN_JOURNAL
5552 || eType==SQLITE_OPEN_WAL
5553 ));
danielk1977fee2d252007-08-18 10:59:19 +00005554
danielk197717b90b52008-06-06 11:11:25 +00005555 /* If argument zPath is a NULL pointer, this function is required to open
5556 ** a temporary file. Use this buffer to store the file name in.
5557 */
drhc02a43a2012-01-10 23:18:38 +00005558 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005559 const char *zName = zPath;
5560
danielk1977fee2d252007-08-18 10:59:19 +00005561 /* Check the following statements are true:
5562 **
5563 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5564 ** (b) if CREATE is set, then READWRITE must also be set, and
5565 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005566 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005567 */
danielk1977b4b47412007-08-17 15:53:36 +00005568 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005569 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005570 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005571 assert(isDelete==0 || isCreate);
5572
danddb0ac42010-07-14 14:48:58 +00005573 /* The main DB, main journal, WAL file and master journal are never
5574 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005575 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5576 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5577 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005578 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005579
danielk1977fee2d252007-08-18 10:59:19 +00005580 /* Assert that the upper layer has set one of the "file-type" flags. */
5581 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5582 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5583 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005584 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005585 );
5586
dan08da86a2009-08-21 17:18:03 +00005587 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005588
dan08da86a2009-08-21 17:18:03 +00005589 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005590 UnixUnusedFd *pUnused;
5591 pUnused = findReusableFd(zName, flags);
5592 if( pUnused ){
5593 fd = pUnused->fd;
5594 }else{
dan6aa657f2009-08-24 18:57:58 +00005595 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005596 if( !pUnused ){
5597 return SQLITE_NOMEM;
5598 }
5599 }
5600 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005601
5602 /* Database filenames are double-zero terminated if they are not
5603 ** URIs with parameters. Hence, they can always be passed into
5604 ** sqlite3_uri_parameter(). */
5605 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5606
dan08da86a2009-08-21 17:18:03 +00005607 }else if( !zName ){
5608 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005609 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005610 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005611 if( rc!=SQLITE_OK ){
5612 return rc;
5613 }
5614 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005615
5616 /* Generated temporary filenames are always double-zero terminated
5617 ** for use by sqlite3_uri_parameter(). */
5618 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005619 }
5620
dan08da86a2009-08-21 17:18:03 +00005621 /* Determine the value of the flags parameter passed to POSIX function
5622 ** open(). These must be calculated even if open() is not called, as
5623 ** they may be stored as part of the file handle and used by the
5624 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005625 if( isReadonly ) openFlags |= O_RDONLY;
5626 if( isReadWrite ) openFlags |= O_RDWR;
5627 if( isCreate ) openFlags |= O_CREAT;
5628 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5629 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005630
danielk1977b4b47412007-08-17 15:53:36 +00005631 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005632 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005633 uid_t uid; /* Userid for the file */
5634 gid_t gid; /* Groupid for the file */
5635 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005636 if( rc!=SQLITE_OK ){
5637 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005638 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005639 return rc;
5640 }
drhad4f1e52011-03-04 15:43:57 +00005641 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005642 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005643 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5644 /* Failed to open the file for read/write access. Try read-only. */
5645 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005646 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005647 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005648 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005649 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005650 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005651 }
5652 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005653 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005654 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005655 }
drhac7c3ac2012-02-11 19:23:48 +00005656
5657 /* If this process is running as root and if creating a new rollback
5658 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005659 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005660 */
5661 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005662 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005663 }
danielk1977b4b47412007-08-17 15:53:36 +00005664 }
dan08da86a2009-08-21 17:18:03 +00005665 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005666 if( pOutFlags ){
5667 *pOutFlags = flags;
5668 }
5669
dane946c392009-08-22 11:39:46 +00005670 if( p->pUnused ){
5671 p->pUnused->fd = fd;
5672 p->pUnused->flags = flags;
5673 }
5674
danielk1977b4b47412007-08-17 15:53:36 +00005675 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005676#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005677 zPath = zName;
5678#else
drh036ac7f2011-08-08 23:18:05 +00005679 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005680#endif
danielk1977b4b47412007-08-17 15:53:36 +00005681 }
drh41022642008-11-21 00:24:42 +00005682#if SQLITE_ENABLE_LOCKING_STYLE
5683 else{
dan08da86a2009-08-21 17:18:03 +00005684 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005685 }
5686#endif
5687
drhda0e7682008-07-30 15:27:54 +00005688 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005689
drh7ed97b92010-01-20 13:07:21 +00005690
5691#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005692 if( fstatfs(fd, &fsInfo) == -1 ){
5693 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005694 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005695 return SQLITE_IOERR_ACCESS;
5696 }
5697 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5698 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5699 }
5700#endif
drhc02a43a2012-01-10 23:18:38 +00005701
5702 /* Set up appropriate ctrlFlags */
5703 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5704 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5705 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5706 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5707 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5708
drh7ed97b92010-01-20 13:07:21 +00005709#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005710#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005711 isAutoProxy = 1;
5712#endif
5713 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005714 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5715 int useProxy = 0;
5716
dan08da86a2009-08-21 17:18:03 +00005717 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5718 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005719 if( envforce!=NULL ){
5720 useProxy = atoi(envforce)>0;
5721 }else{
aswiftaebf4132008-11-21 00:10:35 +00005722 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005723 /* In theory, the close(fd) call is sub-optimal. If the file opened
5724 ** with fd is a database file, and there are other connections open
5725 ** on that file that are currently holding advisory locks on it,
5726 ** then the call to close() will cancel those locks. In practice,
5727 ** we're assuming that statfs() doesn't fail very often. At least
5728 ** not while other file descriptors opened by the same process on
5729 ** the same file are working. */
5730 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005731 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005732 rc = SQLITE_IOERR_ACCESS;
5733 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005734 }
5735 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5736 }
5737 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005738 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005739 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005740 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005741 if( rc!=SQLITE_OK ){
5742 /* Use unixClose to clean up the resources added in fillInUnixFile
5743 ** and clear all the structure's references. Specifically,
5744 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5745 */
5746 unixClose(pFile);
5747 return rc;
5748 }
aswiftaebf4132008-11-21 00:10:35 +00005749 }
dane946c392009-08-22 11:39:46 +00005750 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005751 }
5752 }
5753#endif
5754
drhc02a43a2012-01-10 23:18:38 +00005755 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5756
dane946c392009-08-22 11:39:46 +00005757open_finished:
5758 if( rc!=SQLITE_OK ){
5759 sqlite3_free(p->pUnused);
5760 }
5761 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005762}
5763
dane946c392009-08-22 11:39:46 +00005764
danielk1977b4b47412007-08-17 15:53:36 +00005765/*
danielk1977fee2d252007-08-18 10:59:19 +00005766** Delete the file at zPath. If the dirSync argument is true, fsync()
5767** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005768*/
drh6b9d6dd2008-12-03 19:34:47 +00005769static int unixDelete(
5770 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5771 const char *zPath, /* Name of file to be deleted */
5772 int dirSync /* If true, fsync() directory after deleting file */
5773){
danielk1977fee2d252007-08-18 10:59:19 +00005774 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005775 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005776 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005777 if( osUnlink(zPath)==(-1) ){
5778 if( errno==ENOENT ){
5779 rc = SQLITE_IOERR_DELETE_NOENT;
5780 }else{
drhb4308162012-11-09 21:40:02 +00005781 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005782 }
drhb4308162012-11-09 21:40:02 +00005783 return rc;
drh5d4feff2010-07-14 01:45:22 +00005784 }
danielk1977d39fa702008-10-16 13:27:40 +00005785#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005786 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005787 int fd;
drh90315a22011-08-10 01:52:12 +00005788 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005789 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005790#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005791 if( fsync(fd)==-1 )
5792#else
5793 if( fsync(fd) )
5794#endif
5795 {
dane18d4952011-02-21 11:46:24 +00005796 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005797 }
drh0e9365c2011-03-02 02:08:13 +00005798 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005799 }else if( rc==SQLITE_CANTOPEN ){
5800 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005801 }
5802 }
danielk1977d138dd82008-10-15 16:02:48 +00005803#endif
danielk1977fee2d252007-08-18 10:59:19 +00005804 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005805}
5806
danielk197790949c22007-08-17 16:50:38 +00005807/*
mistachkin48864df2013-03-21 21:20:32 +00005808** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005809** test performed depends on the value of flags:
5810**
5811** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5812** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5813** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5814**
5815** Otherwise return 0.
5816*/
danielk1977861f7452008-06-05 11:39:11 +00005817static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005818 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5819 const char *zPath, /* Path of the file to examine */
5820 int flags, /* What do we want to learn about the zPath file? */
5821 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005822){
rse25c0d1a2007-09-20 08:38:14 +00005823 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005824 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005825 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005826 switch( flags ){
5827 case SQLITE_ACCESS_EXISTS:
5828 amode = F_OK;
5829 break;
5830 case SQLITE_ACCESS_READWRITE:
5831 amode = W_OK|R_OK;
5832 break;
drh50d3f902007-08-27 21:10:36 +00005833 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005834 amode = R_OK;
5835 break;
5836
5837 default:
5838 assert(!"Invalid flags argument");
5839 }
drh99ab3b12011-03-02 15:09:07 +00005840 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005841 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5842 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005843 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005844 *pResOut = 0;
5845 }
5846 }
danielk1977861f7452008-06-05 11:39:11 +00005847 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005848}
5849
danielk1977b4b47412007-08-17 15:53:36 +00005850
5851/*
5852** Turn a relative pathname into a full pathname. The relative path
5853** is stored as a nul-terminated string in the buffer pointed to by
5854** zPath.
5855**
5856** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5857** (in this case, MAX_PATHNAME bytes). The full-path is written to
5858** this buffer before returning.
5859*/
danielk1977adfb9b02007-09-17 07:02:56 +00005860static int unixFullPathname(
5861 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5862 const char *zPath, /* Possibly relative input path */
5863 int nOut, /* Size of output buffer in bytes */
5864 char *zOut /* Output buffer */
5865){
danielk1977843e65f2007-09-01 16:16:15 +00005866
5867 /* It's odd to simulate an io-error here, but really this is just
5868 ** using the io-error infrastructure to test that SQLite handles this
5869 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005870 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005871 */
5872 SimulateIOError( return SQLITE_ERROR );
5873
drh153c62c2007-08-24 03:51:33 +00005874 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005875 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005876
drh3c7f2dc2007-12-06 13:26:20 +00005877 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005878 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005879 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005880 }else{
5881 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005882 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005883 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005884 }
drhea678832008-12-10 19:26:22 +00005885 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005886 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005887 }
5888 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005889}
5890
drh0ccebe72005-06-07 22:22:50 +00005891
drh761df872006-12-21 01:29:22 +00005892#ifndef SQLITE_OMIT_LOAD_EXTENSION
5893/*
5894** Interfaces for opening a shared library, finding entry points
5895** within the shared library, and closing the shared library.
5896*/
5897#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005898static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5899 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005900 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5901}
danielk197795c8a542007-09-01 06:51:27 +00005902
5903/*
5904** SQLite calls this function immediately after a call to unixDlSym() or
5905** unixDlOpen() fails (returns a null pointer). If a more detailed error
5906** message is available, it is written to zBufOut. If no error message
5907** is available, zBufOut is left unmodified and SQLite uses a default
5908** error message.
5909*/
danielk1977397d65f2008-11-19 11:35:39 +00005910static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005911 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005912 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005913 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005914 zErr = dlerror();
5915 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005916 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005917 }
drh6c7d5c52008-11-21 20:32:33 +00005918 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005919}
drh1875f7a2008-12-08 18:19:17 +00005920static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5921 /*
5922 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5923 ** cast into a pointer to a function. And yet the library dlsym() routine
5924 ** returns a void* which is really a pointer to a function. So how do we
5925 ** use dlsym() with -pedantic-errors?
5926 **
5927 ** Variable x below is defined to be a pointer to a function taking
5928 ** parameters void* and const char* and returning a pointer to a function.
5929 ** We initialize x by assigning it a pointer to the dlsym() function.
5930 ** (That assignment requires a cast.) Then we call the function that
5931 ** x points to.
5932 **
5933 ** This work-around is unlikely to work correctly on any system where
5934 ** you really cannot cast a function pointer into void*. But then, on the
5935 ** other hand, dlsym() will not work on such a system either, so we have
5936 ** not really lost anything.
5937 */
5938 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005939 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005940 x = (void(*(*)(void*,const char*))(void))dlsym;
5941 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005942}
danielk1977397d65f2008-11-19 11:35:39 +00005943static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5944 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005945 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005946}
danielk1977b4b47412007-08-17 15:53:36 +00005947#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5948 #define unixDlOpen 0
5949 #define unixDlError 0
5950 #define unixDlSym 0
5951 #define unixDlClose 0
5952#endif
5953
5954/*
danielk197790949c22007-08-17 16:50:38 +00005955** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005956*/
danielk1977397d65f2008-11-19 11:35:39 +00005957static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5958 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005959 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005960
drhbbd42a62004-05-22 17:41:58 +00005961 /* We have to initialize zBuf to prevent valgrind from reporting
5962 ** errors. The reports issued by valgrind are incorrect - we would
5963 ** prefer that the randomness be increased by making use of the
5964 ** uninitialized space in zBuf - but valgrind errors tend to worry
5965 ** some users. Rather than argue, it seems easier just to initialize
5966 ** the whole array and silence valgrind, even if that means less randomness
5967 ** in the random seed.
5968 **
5969 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005970 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005971 ** tests repeatable.
5972 */
danielk1977b4b47412007-08-17 15:53:36 +00005973 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005974#if !defined(SQLITE_TEST)
5975 {
drhc18b4042012-02-10 03:10:27 +00005976 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005977 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005978 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005979 time_t t;
5980 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005981 memcpy(zBuf, &t, sizeof(t));
5982 pid = getpid();
5983 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005984 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005985 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005986 }else{
drhc18b4042012-02-10 03:10:27 +00005987 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005988 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005989 }
drhbbd42a62004-05-22 17:41:58 +00005990 }
5991#endif
drh72cbd072008-10-14 17:58:38 +00005992 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005993}
5994
danielk1977b4b47412007-08-17 15:53:36 +00005995
drhbbd42a62004-05-22 17:41:58 +00005996/*
5997** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005998** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005999** The return value is the number of microseconds of sleep actually
6000** requested from the underlying operating system, a number which
6001** might be greater than or equal to the argument, but not less
6002** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006003*/
danielk1977397d65f2008-11-19 11:35:39 +00006004static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006005#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006006 struct timespec sp;
6007
6008 sp.tv_sec = microseconds / 1000000;
6009 sp.tv_nsec = (microseconds % 1000000) * 1000;
6010 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006011 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006012 return microseconds;
6013#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006014 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006015 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006016 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006017#else
danielk1977b4b47412007-08-17 15:53:36 +00006018 int seconds = (microseconds+999999)/1000000;
6019 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006020 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006021 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006022#endif
drh88f474a2006-01-02 20:00:12 +00006023}
6024
6025/*
drh6b9d6dd2008-12-03 19:34:47 +00006026** The following variable, if set to a non-zero value, is interpreted as
6027** the number of seconds since 1970 and is used to set the result of
6028** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006029*/
6030#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006031int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006032#endif
6033
6034/*
drhb7e8ea22010-05-03 14:32:30 +00006035** Find the current time (in Universal Coordinated Time). Write into *piNow
6036** the current time and date as a Julian Day number times 86_400_000. In
6037** other words, write into *piNow the number of milliseconds since the Julian
6038** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6039** proleptic Gregorian calendar.
6040**
drh31702252011-10-12 23:13:43 +00006041** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6042** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006043*/
6044static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6045 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006046 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006047#if defined(NO_GETTOD)
6048 time_t t;
6049 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006050 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006051#elif OS_VXWORKS
6052 struct timespec sNow;
6053 clock_gettime(CLOCK_REALTIME, &sNow);
6054 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6055#else
6056 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006057 if( gettimeofday(&sNow, 0)==0 ){
6058 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6059 }else{
6060 rc = SQLITE_ERROR;
6061 }
drhb7e8ea22010-05-03 14:32:30 +00006062#endif
6063
6064#ifdef SQLITE_TEST
6065 if( sqlite3_current_time ){
6066 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6067 }
6068#endif
6069 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006070 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006071}
6072
6073/*
drhbbd42a62004-05-22 17:41:58 +00006074** Find the current time (in Universal Coordinated Time). Write the
6075** current time and date as a Julian Day number into *prNow and
6076** return 0. Return 1 if the time and date cannot be found.
6077*/
danielk1977397d65f2008-11-19 11:35:39 +00006078static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006079 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006080 int rc;
drhff828942010-06-26 21:34:06 +00006081 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006082 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006083 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006084 return rc;
drhbbd42a62004-05-22 17:41:58 +00006085}
danielk1977b4b47412007-08-17 15:53:36 +00006086
drh6b9d6dd2008-12-03 19:34:47 +00006087/*
6088** We added the xGetLastError() method with the intention of providing
6089** better low-level error messages when operating-system problems come up
6090** during SQLite operation. But so far, none of that has been implemented
6091** in the core. So this routine is never called. For now, it is merely
6092** a place-holder.
6093*/
danielk1977397d65f2008-11-19 11:35:39 +00006094static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6095 UNUSED_PARAMETER(NotUsed);
6096 UNUSED_PARAMETER(NotUsed2);
6097 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006098 return 0;
6099}
6100
drhf2424c52010-04-26 00:04:55 +00006101
6102/*
drh734c9862008-11-28 15:37:20 +00006103************************ End of sqlite3_vfs methods ***************************
6104******************************************************************************/
6105
drh715ff302008-12-03 22:32:44 +00006106/******************************************************************************
6107************************** Begin Proxy Locking ********************************
6108**
6109** Proxy locking is a "uber-locking-method" in this sense: It uses the
6110** other locking methods on secondary lock files. Proxy locking is a
6111** meta-layer over top of the primitive locking implemented above. For
6112** this reason, the division that implements of proxy locking is deferred
6113** until late in the file (here) after all of the other I/O methods have
6114** been defined - so that the primitive locking methods are available
6115** as services to help with the implementation of proxy locking.
6116**
6117****
6118**
6119** The default locking schemes in SQLite use byte-range locks on the
6120** database file to coordinate safe, concurrent access by multiple readers
6121** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6122** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6123** as POSIX read & write locks over fixed set of locations (via fsctl),
6124** on AFP and SMB only exclusive byte-range locks are available via fsctl
6125** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6126** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6127** address in the shared range is taken for a SHARED lock, the entire
6128** shared range is taken for an EXCLUSIVE lock):
6129**
drhf2f105d2012-08-20 15:53:54 +00006130** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006131** RESERVED_BYTE 0x40000001
6132** SHARED_RANGE 0x40000002 -> 0x40000200
6133**
6134** This works well on the local file system, but shows a nearly 100x
6135** slowdown in read performance on AFP because the AFP client disables
6136** the read cache when byte-range locks are present. Enabling the read
6137** cache exposes a cache coherency problem that is present on all OS X
6138** supported network file systems. NFS and AFP both observe the
6139** close-to-open semantics for ensuring cache coherency
6140** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6141** address the requirements for concurrent database access by multiple
6142** readers and writers
6143** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6144**
6145** To address the performance and cache coherency issues, proxy file locking
6146** changes the way database access is controlled by limiting access to a
6147** single host at a time and moving file locks off of the database file
6148** and onto a proxy file on the local file system.
6149**
6150**
6151** Using proxy locks
6152** -----------------
6153**
6154** C APIs
6155**
6156** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6157** <proxy_path> | ":auto:");
6158** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6159**
6160**
6161** SQL pragmas
6162**
6163** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6164** PRAGMA [database.]lock_proxy_file
6165**
6166** Specifying ":auto:" means that if there is a conch file with a matching
6167** host ID in it, the proxy path in the conch file will be used, otherwise
6168** a proxy path based on the user's temp dir
6169** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6170** actual proxy file name is generated from the name and path of the
6171** database file. For example:
6172**
6173** For database path "/Users/me/foo.db"
6174** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6175**
6176** Once a lock proxy is configured for a database connection, it can not
6177** be removed, however it may be switched to a different proxy path via
6178** the above APIs (assuming the conch file is not being held by another
6179** connection or process).
6180**
6181**
6182** How proxy locking works
6183** -----------------------
6184**
6185** Proxy file locking relies primarily on two new supporting files:
6186**
6187** * conch file to limit access to the database file to a single host
6188** at a time
6189**
6190** * proxy file to act as a proxy for the advisory locks normally
6191** taken on the database
6192**
6193** The conch file - to use a proxy file, sqlite must first "hold the conch"
6194** by taking an sqlite-style shared lock on the conch file, reading the
6195** contents and comparing the host's unique host ID (see below) and lock
6196** proxy path against the values stored in the conch. The conch file is
6197** stored in the same directory as the database file and the file name
6198** is patterned after the database file name as ".<databasename>-conch".
6199** If the conch file does not exist, or it's contents do not match the
6200** host ID and/or proxy path, then the lock is escalated to an exclusive
6201** lock and the conch file contents is updated with the host ID and proxy
6202** path and the lock is downgraded to a shared lock again. If the conch
6203** is held by another process (with a shared lock), the exclusive lock
6204** will fail and SQLITE_BUSY is returned.
6205**
6206** The proxy file - a single-byte file used for all advisory file locks
6207** normally taken on the database file. This allows for safe sharing
6208** of the database file for multiple readers and writers on the same
6209** host (the conch ensures that they all use the same local lock file).
6210**
drh715ff302008-12-03 22:32:44 +00006211** Requesting the lock proxy does not immediately take the conch, it is
6212** only taken when the first request to lock database file is made.
6213** This matches the semantics of the traditional locking behavior, where
6214** opening a connection to a database file does not take a lock on it.
6215** The shared lock and an open file descriptor are maintained until
6216** the connection to the database is closed.
6217**
6218** The proxy file and the lock file are never deleted so they only need
6219** to be created the first time they are used.
6220**
6221** Configuration options
6222** ---------------------
6223**
6224** SQLITE_PREFER_PROXY_LOCKING
6225**
6226** Database files accessed on non-local file systems are
6227** automatically configured for proxy locking, lock files are
6228** named automatically using the same logic as
6229** PRAGMA lock_proxy_file=":auto:"
6230**
6231** SQLITE_PROXY_DEBUG
6232**
6233** Enables the logging of error messages during host id file
6234** retrieval and creation
6235**
drh715ff302008-12-03 22:32:44 +00006236** LOCKPROXYDIR
6237**
6238** Overrides the default directory used for lock proxy files that
6239** are named automatically via the ":auto:" setting
6240**
6241** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6242**
6243** Permissions to use when creating a directory for storing the
6244** lock proxy files, only used when LOCKPROXYDIR is not set.
6245**
6246**
6247** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6248** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6249** force proxy locking to be used for every database file opened, and 0
6250** will force automatic proxy locking to be disabled for all database
6251** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6252** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6253*/
6254
6255/*
6256** Proxy locking is only available on MacOSX
6257*/
drhd2cb50b2009-01-09 21:41:17 +00006258#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006259
drh715ff302008-12-03 22:32:44 +00006260/*
6261** The proxyLockingContext has the path and file structures for the remote
6262** and local proxy files in it
6263*/
6264typedef struct proxyLockingContext proxyLockingContext;
6265struct proxyLockingContext {
6266 unixFile *conchFile; /* Open conch file */
6267 char *conchFilePath; /* Name of the conch file */
6268 unixFile *lockProxy; /* Open proxy lock file */
6269 char *lockProxyPath; /* Name of the proxy lock file */
6270 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006271 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006272 void *oldLockingContext; /* Original lockingcontext to restore on close */
6273 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6274};
6275
drh7ed97b92010-01-20 13:07:21 +00006276/*
6277** The proxy lock file path for the database at dbPath is written into lPath,
6278** which must point to valid, writable memory large enough for a maxLen length
6279** file path.
drh715ff302008-12-03 22:32:44 +00006280*/
drh715ff302008-12-03 22:32:44 +00006281static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6282 int len;
6283 int dbLen;
6284 int i;
6285
6286#ifdef LOCKPROXYDIR
6287 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6288#else
6289# ifdef _CS_DARWIN_USER_TEMP_DIR
6290 {
drh7ed97b92010-01-20 13:07:21 +00006291 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006292 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6293 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006294 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006295 }
drh7ed97b92010-01-20 13:07:21 +00006296 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006297 }
6298# else
6299 len = strlcpy(lPath, "/tmp/", maxLen);
6300# endif
6301#endif
6302
6303 if( lPath[len-1]!='/' ){
6304 len = strlcat(lPath, "/", maxLen);
6305 }
6306
6307 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006308 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006309 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006310 char c = dbPath[i];
6311 lPath[i+len] = (c=='/')?'_':c;
6312 }
6313 lPath[i+len]='\0';
6314 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006315 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006316 return SQLITE_OK;
6317}
6318
drh7ed97b92010-01-20 13:07:21 +00006319/*
6320 ** Creates the lock file and any missing directories in lockPath
6321 */
6322static int proxyCreateLockPath(const char *lockPath){
6323 int i, len;
6324 char buf[MAXPATHLEN];
6325 int start = 0;
6326
6327 assert(lockPath!=NULL);
6328 /* try to create all the intermediate directories */
6329 len = (int)strlen(lockPath);
6330 buf[0] = lockPath[0];
6331 for( i=1; i<len; i++ ){
6332 if( lockPath[i] == '/' && (i - start > 0) ){
6333 /* only mkdir if leaf dir != "." or "/" or ".." */
6334 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6335 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6336 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006337 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006338 int err=errno;
6339 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006340 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006341 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006342 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006343 return err;
6344 }
6345 }
6346 }
6347 start=i+1;
6348 }
6349 buf[i] = lockPath[i];
6350 }
drh308c2a52010-05-14 11:30:18 +00006351 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006352 return 0;
6353}
6354
drh715ff302008-12-03 22:32:44 +00006355/*
6356** Create a new VFS file descriptor (stored in memory obtained from
6357** sqlite3_malloc) and open the file named "path" in the file descriptor.
6358**
6359** The caller is responsible not only for closing the file descriptor
6360** but also for freeing the memory associated with the file descriptor.
6361*/
drh7ed97b92010-01-20 13:07:21 +00006362static int proxyCreateUnixFile(
6363 const char *path, /* path for the new unixFile */
6364 unixFile **ppFile, /* unixFile created and returned by ref */
6365 int islockfile /* if non zero missing dirs will be created */
6366) {
6367 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006368 unixFile *pNew;
6369 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006370 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006371 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006372 int terrno = 0;
6373 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006374
drh7ed97b92010-01-20 13:07:21 +00006375 /* 1. first try to open/create the file
6376 ** 2. if that fails, and this is a lock file (not-conch), try creating
6377 ** the parent directories and then try again.
6378 ** 3. if that fails, try to open the file read-only
6379 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6380 */
6381 pUnused = findReusableFd(path, openFlags);
6382 if( pUnused ){
6383 fd = pUnused->fd;
6384 }else{
6385 pUnused = sqlite3_malloc(sizeof(*pUnused));
6386 if( !pUnused ){
6387 return SQLITE_NOMEM;
6388 }
6389 }
6390 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006391 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006392 terrno = errno;
6393 if( fd<0 && errno==ENOENT && islockfile ){
6394 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006395 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006396 }
6397 }
6398 }
6399 if( fd<0 ){
6400 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006401 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006402 terrno = errno;
6403 }
6404 if( fd<0 ){
6405 if( islockfile ){
6406 return SQLITE_BUSY;
6407 }
6408 switch (terrno) {
6409 case EACCES:
6410 return SQLITE_PERM;
6411 case EIO:
6412 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6413 default:
drh9978c972010-02-23 17:36:32 +00006414 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006415 }
6416 }
6417
6418 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6419 if( pNew==NULL ){
6420 rc = SQLITE_NOMEM;
6421 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006422 }
6423 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006424 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006425 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006426 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006427 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006428 pUnused->fd = fd;
6429 pUnused->flags = openFlags;
6430 pNew->pUnused = pUnused;
6431
drhc02a43a2012-01-10 23:18:38 +00006432 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006433 if( rc==SQLITE_OK ){
6434 *ppFile = pNew;
6435 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006436 }
drh7ed97b92010-01-20 13:07:21 +00006437end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006438 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006439 sqlite3_free(pNew);
6440 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006441 return rc;
6442}
6443
drh7ed97b92010-01-20 13:07:21 +00006444#ifdef SQLITE_TEST
6445/* simulate multiple hosts by creating unique hostid file paths */
6446int sqlite3_hostid_num = 0;
6447#endif
6448
6449#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6450
drh0ab216a2010-07-02 17:10:40 +00006451/* Not always defined in the headers as it ought to be */
6452extern int gethostuuid(uuid_t id, const struct timespec *wait);
6453
drh7ed97b92010-01-20 13:07:21 +00006454/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6455** bytes of writable memory.
6456*/
6457static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006458 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6459 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006460#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6461 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006462 {
6463 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6464 if( gethostuuid(pHostID, &timeout) ){
6465 int err = errno;
6466 if( pError ){
6467 *pError = err;
6468 }
6469 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006470 }
drh7ed97b92010-01-20 13:07:21 +00006471 }
drh3d4435b2011-08-26 20:55:50 +00006472#else
6473 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006474#endif
drh7ed97b92010-01-20 13:07:21 +00006475#ifdef SQLITE_TEST
6476 /* simulate multiple hosts by creating unique hostid file paths */
6477 if( sqlite3_hostid_num != 0){
6478 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6479 }
6480#endif
6481
6482 return SQLITE_OK;
6483}
6484
6485/* The conch file contains the header, host id and lock file path
6486 */
6487#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6488#define PROXY_HEADERLEN 1 /* conch file header length */
6489#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6490#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6491
6492/*
6493** Takes an open conch file, copies the contents to a new path and then moves
6494** it back. The newly created file's file descriptor is assigned to the
6495** conch file structure and finally the original conch file descriptor is
6496** closed. Returns zero if successful.
6497*/
6498static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6499 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6500 unixFile *conchFile = pCtx->conchFile;
6501 char tPath[MAXPATHLEN];
6502 char buf[PROXY_MAXCONCHLEN];
6503 char *cPath = pCtx->conchFilePath;
6504 size_t readLen = 0;
6505 size_t pathLen = 0;
6506 char errmsg[64] = "";
6507 int fd = -1;
6508 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006509 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006510
6511 /* create a new path by replace the trailing '-conch' with '-break' */
6512 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6513 if( pathLen>MAXPATHLEN || pathLen<6 ||
6514 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006515 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006516 goto end_breaklock;
6517 }
6518 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006519 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006520 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006521 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006522 goto end_breaklock;
6523 }
6524 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006525 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006526 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006527 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006528 goto end_breaklock;
6529 }
drhe562be52011-03-02 18:01:10 +00006530 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006531 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006532 goto end_breaklock;
6533 }
6534 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006535 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006536 goto end_breaklock;
6537 }
6538 rc = 0;
6539 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006540 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006541 conchFile->h = fd;
6542 conchFile->openFlags = O_RDWR | O_CREAT;
6543
6544end_breaklock:
6545 if( rc ){
6546 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006547 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006548 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006549 }
6550 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6551 }
6552 return rc;
6553}
6554
6555/* Take the requested lock on the conch file and break a stale lock if the
6556** host id matches.
6557*/
6558static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6559 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6560 unixFile *conchFile = pCtx->conchFile;
6561 int rc = SQLITE_OK;
6562 int nTries = 0;
6563 struct timespec conchModTime;
6564
drh3d4435b2011-08-26 20:55:50 +00006565 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006566 do {
6567 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6568 nTries ++;
6569 if( rc==SQLITE_BUSY ){
6570 /* If the lock failed (busy):
6571 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6572 * 2nd try: fail if the mod time changed or host id is different, wait
6573 * 10 sec and try again
6574 * 3rd try: break the lock unless the mod time has changed.
6575 */
6576 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006577 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006578 pFile->lastErrno = errno;
6579 return SQLITE_IOERR_LOCK;
6580 }
6581
6582 if( nTries==1 ){
6583 conchModTime = buf.st_mtimespec;
6584 usleep(500000); /* wait 0.5 sec and try the lock again*/
6585 continue;
6586 }
6587
6588 assert( nTries>1 );
6589 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6590 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6591 return SQLITE_BUSY;
6592 }
6593
6594 if( nTries==2 ){
6595 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006596 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006597 if( len<0 ){
6598 pFile->lastErrno = errno;
6599 return SQLITE_IOERR_LOCK;
6600 }
6601 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6602 /* don't break the lock if the host id doesn't match */
6603 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6604 return SQLITE_BUSY;
6605 }
6606 }else{
6607 /* don't break the lock on short read or a version mismatch */
6608 return SQLITE_BUSY;
6609 }
6610 usleep(10000000); /* wait 10 sec and try the lock again */
6611 continue;
6612 }
6613
6614 assert( nTries==3 );
6615 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6616 rc = SQLITE_OK;
6617 if( lockType==EXCLUSIVE_LOCK ){
6618 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6619 }
6620 if( !rc ){
6621 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6622 }
6623 }
6624 }
6625 } while( rc==SQLITE_BUSY && nTries<3 );
6626
6627 return rc;
6628}
6629
6630/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006631** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6632** lockPath means that the lockPath in the conch file will be used if the
6633** host IDs match, or a new lock path will be generated automatically
6634** and written to the conch file.
6635*/
6636static int proxyTakeConch(unixFile *pFile){
6637 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6638
drh7ed97b92010-01-20 13:07:21 +00006639 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006640 return SQLITE_OK;
6641 }else{
6642 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006643 uuid_t myHostID;
6644 int pError = 0;
6645 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006646 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006647 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006648 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006649 int createConch = 0;
6650 int hostIdMatch = 0;
6651 int readLen = 0;
6652 int tryOldLockPath = 0;
6653 int forceNewLockPath = 0;
6654
drh308c2a52010-05-14 11:30:18 +00006655 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6656 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006657
drh7ed97b92010-01-20 13:07:21 +00006658 rc = proxyGetHostID(myHostID, &pError);
6659 if( (rc&0xff)==SQLITE_IOERR ){
6660 pFile->lastErrno = pError;
6661 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006662 }
drh7ed97b92010-01-20 13:07:21 +00006663 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006664 if( rc!=SQLITE_OK ){
6665 goto end_takeconch;
6666 }
drh7ed97b92010-01-20 13:07:21 +00006667 /* read the existing conch file */
6668 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6669 if( readLen<0 ){
6670 /* I/O error: lastErrno set by seekAndRead */
6671 pFile->lastErrno = conchFile->lastErrno;
6672 rc = SQLITE_IOERR_READ;
6673 goto end_takeconch;
6674 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6675 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6676 /* a short read or version format mismatch means we need to create a new
6677 ** conch file.
6678 */
6679 createConch = 1;
6680 }
6681 /* if the host id matches and the lock path already exists in the conch
6682 ** we'll try to use the path there, if we can't open that path, we'll
6683 ** retry with a new auto-generated path
6684 */
6685 do { /* in case we need to try again for an :auto: named lock file */
6686
6687 if( !createConch && !forceNewLockPath ){
6688 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6689 PROXY_HOSTIDLEN);
6690 /* if the conch has data compare the contents */
6691 if( !pCtx->lockProxyPath ){
6692 /* for auto-named local lock file, just check the host ID and we'll
6693 ** use the local lock file path that's already in there
6694 */
6695 if( hostIdMatch ){
6696 size_t pathLen = (readLen - PROXY_PATHINDEX);
6697
6698 if( pathLen>=MAXPATHLEN ){
6699 pathLen=MAXPATHLEN-1;
6700 }
6701 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6702 lockPath[pathLen] = 0;
6703 tempLockPath = lockPath;
6704 tryOldLockPath = 1;
6705 /* create a copy of the lock path if the conch is taken */
6706 goto end_takeconch;
6707 }
6708 }else if( hostIdMatch
6709 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6710 readLen-PROXY_PATHINDEX)
6711 ){
6712 /* conch host and lock path match */
6713 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006714 }
drh7ed97b92010-01-20 13:07:21 +00006715 }
6716
6717 /* if the conch isn't writable and doesn't match, we can't take it */
6718 if( (conchFile->openFlags&O_RDWR) == 0 ){
6719 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006720 goto end_takeconch;
6721 }
drh7ed97b92010-01-20 13:07:21 +00006722
6723 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006724 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006725 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6726 tempLockPath = lockPath;
6727 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006728 }
drh7ed97b92010-01-20 13:07:21 +00006729
6730 /* update conch with host and path (this will fail if other process
6731 ** has a shared lock already), if the host id matches, use the big
6732 ** stick.
drh715ff302008-12-03 22:32:44 +00006733 */
drh7ed97b92010-01-20 13:07:21 +00006734 futimes(conchFile->h, NULL);
6735 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006736 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006737 /* We are trying for an exclusive lock but another thread in this
6738 ** same process is still holding a shared lock. */
6739 rc = SQLITE_BUSY;
6740 } else {
6741 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006742 }
drh715ff302008-12-03 22:32:44 +00006743 }else{
drh7ed97b92010-01-20 13:07:21 +00006744 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006745 }
drh7ed97b92010-01-20 13:07:21 +00006746 if( rc==SQLITE_OK ){
6747 char writeBuffer[PROXY_MAXCONCHLEN];
6748 int writeSize = 0;
6749
6750 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6751 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6752 if( pCtx->lockProxyPath!=NULL ){
6753 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6754 }else{
6755 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6756 }
6757 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006758 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006759 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6760 fsync(conchFile->h);
6761 /* If we created a new conch file (not just updated the contents of a
6762 ** valid conch file), try to match the permissions of the database
6763 */
6764 if( rc==SQLITE_OK && createConch ){
6765 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006766 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006767 if( err==0 ){
6768 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6769 S_IROTH|S_IWOTH);
6770 /* try to match the database file R/W permissions, ignore failure */
6771#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006772 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006773#else
drhff812312011-02-23 13:33:46 +00006774 do{
drhe562be52011-03-02 18:01:10 +00006775 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006776 }while( rc==(-1) && errno==EINTR );
6777 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006778 int code = errno;
6779 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6780 cmode, code, strerror(code));
6781 } else {
6782 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6783 }
6784 }else{
6785 int code = errno;
6786 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6787 err, code, strerror(code));
6788#endif
6789 }
drh715ff302008-12-03 22:32:44 +00006790 }
6791 }
drh7ed97b92010-01-20 13:07:21 +00006792 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6793
6794 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006795 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006796 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006797 int fd;
drh7ed97b92010-01-20 13:07:21 +00006798 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006799 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006800 }
6801 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006802 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006803 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006804 if( fd>=0 ){
6805 pFile->h = fd;
6806 }else{
drh9978c972010-02-23 17:36:32 +00006807 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006808 during locking */
6809 }
6810 }
6811 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6812 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6813 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6814 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6815 /* we couldn't create the proxy lock file with the old lock file path
6816 ** so try again via auto-naming
6817 */
6818 forceNewLockPath = 1;
6819 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006820 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006821 }
6822 }
6823 if( rc==SQLITE_OK ){
6824 /* Need to make a copy of path if we extracted the value
6825 ** from the conch file or the path was allocated on the stack
6826 */
6827 if( tempLockPath ){
6828 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6829 if( !pCtx->lockProxyPath ){
6830 rc = SQLITE_NOMEM;
6831 }
6832 }
6833 }
6834 if( rc==SQLITE_OK ){
6835 pCtx->conchHeld = 1;
6836
6837 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6838 afpLockingContext *afpCtx;
6839 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6840 afpCtx->dbPath = pCtx->lockProxyPath;
6841 }
6842 } else {
6843 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6844 }
drh308c2a52010-05-14 11:30:18 +00006845 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6846 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006847 return rc;
drh308c2a52010-05-14 11:30:18 +00006848 } while (1); /* in case we need to retry the :auto: lock file -
6849 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006850 }
6851}
6852
6853/*
6854** If pFile holds a lock on a conch file, then release that lock.
6855*/
6856static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006857 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006858 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6859 unixFile *conchFile; /* Name of the conch file */
6860
6861 pCtx = (proxyLockingContext *)pFile->lockingContext;
6862 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006863 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006864 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006865 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006866 if( pCtx->conchHeld>0 ){
6867 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6868 }
drh715ff302008-12-03 22:32:44 +00006869 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006870 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6871 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006872 return rc;
6873}
6874
6875/*
6876** Given the name of a database file, compute the name of its conch file.
6877** Store the conch filename in memory obtained from sqlite3_malloc().
6878** Make *pConchPath point to the new name. Return SQLITE_OK on success
6879** or SQLITE_NOMEM if unable to obtain memory.
6880**
6881** The caller is responsible for ensuring that the allocated memory
6882** space is eventually freed.
6883**
6884** *pConchPath is set to NULL if a memory allocation error occurs.
6885*/
6886static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6887 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006888 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006889 char *conchPath; /* buffer in which to construct conch name */
6890
6891 /* Allocate space for the conch filename and initialize the name to
6892 ** the name of the original database file. */
6893 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6894 if( conchPath==0 ){
6895 return SQLITE_NOMEM;
6896 }
6897 memcpy(conchPath, dbPath, len+1);
6898
6899 /* now insert a "." before the last / character */
6900 for( i=(len-1); i>=0; i-- ){
6901 if( conchPath[i]=='/' ){
6902 i++;
6903 break;
6904 }
6905 }
6906 conchPath[i]='.';
6907 while ( i<len ){
6908 conchPath[i+1]=dbPath[i];
6909 i++;
6910 }
6911
6912 /* append the "-conch" suffix to the file */
6913 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006914 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006915
6916 return SQLITE_OK;
6917}
6918
6919
6920/* Takes a fully configured proxy locking-style unix file and switches
6921** the local lock file path
6922*/
6923static int switchLockProxyPath(unixFile *pFile, const char *path) {
6924 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6925 char *oldPath = pCtx->lockProxyPath;
6926 int rc = SQLITE_OK;
6927
drh308c2a52010-05-14 11:30:18 +00006928 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006929 return SQLITE_BUSY;
6930 }
6931
6932 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6933 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6934 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6935 return SQLITE_OK;
6936 }else{
6937 unixFile *lockProxy = pCtx->lockProxy;
6938 pCtx->lockProxy=NULL;
6939 pCtx->conchHeld = 0;
6940 if( lockProxy!=NULL ){
6941 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6942 if( rc ) return rc;
6943 sqlite3_free(lockProxy);
6944 }
6945 sqlite3_free(oldPath);
6946 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6947 }
6948
6949 return rc;
6950}
6951
6952/*
6953** pFile is a file that has been opened by a prior xOpen call. dbPath
6954** is a string buffer at least MAXPATHLEN+1 characters in size.
6955**
6956** This routine find the filename associated with pFile and writes it
6957** int dbPath.
6958*/
6959static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006960#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006961 if( pFile->pMethod == &afpIoMethods ){
6962 /* afp style keeps a reference to the db path in the filePath field
6963 ** of the struct */
drhea678832008-12-10 19:26:22 +00006964 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006965 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6966 } else
drh715ff302008-12-03 22:32:44 +00006967#endif
6968 if( pFile->pMethod == &dotlockIoMethods ){
6969 /* dot lock style uses the locking context to store the dot lock
6970 ** file path */
6971 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6972 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6973 }else{
6974 /* all other styles use the locking context to store the db file path */
6975 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006976 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006977 }
6978 return SQLITE_OK;
6979}
6980
6981/*
6982** Takes an already filled in unix file and alters it so all file locking
6983** will be performed on the local proxy lock file. The following fields
6984** are preserved in the locking context so that they can be restored and
6985** the unix structure properly cleaned up at close time:
6986** ->lockingContext
6987** ->pMethod
6988*/
6989static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6990 proxyLockingContext *pCtx;
6991 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6992 char *lockPath=NULL;
6993 int rc = SQLITE_OK;
6994
drh308c2a52010-05-14 11:30:18 +00006995 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006996 return SQLITE_BUSY;
6997 }
6998 proxyGetDbPathForUnixFile(pFile, dbPath);
6999 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7000 lockPath=NULL;
7001 }else{
7002 lockPath=(char *)path;
7003 }
7004
drh308c2a52010-05-14 11:30:18 +00007005 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7006 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007007
7008 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7009 if( pCtx==0 ){
7010 return SQLITE_NOMEM;
7011 }
7012 memset(pCtx, 0, sizeof(*pCtx));
7013
7014 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7015 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007016 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7017 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7018 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7019 ** (c) the file system is read-only, then enable no-locking access.
7020 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7021 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7022 */
7023 struct statfs fsInfo;
7024 struct stat conchInfo;
7025 int goLockless = 0;
7026
drh99ab3b12011-03-02 15:09:07 +00007027 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007028 int err = errno;
7029 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7030 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7031 }
7032 }
7033 if( goLockless ){
7034 pCtx->conchHeld = -1; /* read only FS/ lockless */
7035 rc = SQLITE_OK;
7036 }
7037 }
drh715ff302008-12-03 22:32:44 +00007038 }
7039 if( rc==SQLITE_OK && lockPath ){
7040 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7041 }
7042
7043 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007044 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7045 if( pCtx->dbPath==NULL ){
7046 rc = SQLITE_NOMEM;
7047 }
7048 }
7049 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007050 /* all memory is allocated, proxys are created and assigned,
7051 ** switch the locking context and pMethod then return.
7052 */
drh715ff302008-12-03 22:32:44 +00007053 pCtx->oldLockingContext = pFile->lockingContext;
7054 pFile->lockingContext = pCtx;
7055 pCtx->pOldMethod = pFile->pMethod;
7056 pFile->pMethod = &proxyIoMethods;
7057 }else{
7058 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007059 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007060 sqlite3_free(pCtx->conchFile);
7061 }
drhd56b1212010-08-11 06:14:15 +00007062 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007063 sqlite3_free(pCtx->conchFilePath);
7064 sqlite3_free(pCtx);
7065 }
drh308c2a52010-05-14 11:30:18 +00007066 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7067 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007068 return rc;
7069}
7070
7071
7072/*
7073** This routine handles sqlite3_file_control() calls that are specific
7074** to proxy locking.
7075*/
7076static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7077 switch( op ){
7078 case SQLITE_GET_LOCKPROXYFILE: {
7079 unixFile *pFile = (unixFile*)id;
7080 if( pFile->pMethod == &proxyIoMethods ){
7081 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7082 proxyTakeConch(pFile);
7083 if( pCtx->lockProxyPath ){
7084 *(const char **)pArg = pCtx->lockProxyPath;
7085 }else{
7086 *(const char **)pArg = ":auto: (not held)";
7087 }
7088 } else {
7089 *(const char **)pArg = NULL;
7090 }
7091 return SQLITE_OK;
7092 }
7093 case SQLITE_SET_LOCKPROXYFILE: {
7094 unixFile *pFile = (unixFile*)id;
7095 int rc = SQLITE_OK;
7096 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7097 if( pArg==NULL || (const char *)pArg==0 ){
7098 if( isProxyStyle ){
7099 /* turn off proxy locking - not supported */
7100 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7101 }else{
7102 /* turn off proxy locking - already off - NOOP */
7103 rc = SQLITE_OK;
7104 }
7105 }else{
7106 const char *proxyPath = (const char *)pArg;
7107 if( isProxyStyle ){
7108 proxyLockingContext *pCtx =
7109 (proxyLockingContext*)pFile->lockingContext;
7110 if( !strcmp(pArg, ":auto:")
7111 || (pCtx->lockProxyPath &&
7112 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7113 ){
7114 rc = SQLITE_OK;
7115 }else{
7116 rc = switchLockProxyPath(pFile, proxyPath);
7117 }
7118 }else{
7119 /* turn on proxy file locking */
7120 rc = proxyTransformUnixFile(pFile, proxyPath);
7121 }
7122 }
7123 return rc;
7124 }
7125 default: {
7126 assert( 0 ); /* The call assures that only valid opcodes are sent */
7127 }
7128 }
7129 /*NOTREACHED*/
7130 return SQLITE_ERROR;
7131}
7132
7133/*
7134** Within this division (the proxying locking implementation) the procedures
7135** above this point are all utilities. The lock-related methods of the
7136** proxy-locking sqlite3_io_method object follow.
7137*/
7138
7139
7140/*
7141** This routine checks if there is a RESERVED lock held on the specified
7142** file by this or any other process. If such a lock is held, set *pResOut
7143** to a non-zero value otherwise *pResOut is set to zero. The return value
7144** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7145*/
7146static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7147 unixFile *pFile = (unixFile*)id;
7148 int rc = proxyTakeConch(pFile);
7149 if( rc==SQLITE_OK ){
7150 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007151 if( pCtx->conchHeld>0 ){
7152 unixFile *proxy = pCtx->lockProxy;
7153 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7154 }else{ /* conchHeld < 0 is lockless */
7155 pResOut=0;
7156 }
drh715ff302008-12-03 22:32:44 +00007157 }
7158 return rc;
7159}
7160
7161/*
drh308c2a52010-05-14 11:30:18 +00007162** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007163** of the following:
7164**
7165** (1) SHARED_LOCK
7166** (2) RESERVED_LOCK
7167** (3) PENDING_LOCK
7168** (4) EXCLUSIVE_LOCK
7169**
7170** Sometimes when requesting one lock state, additional lock states
7171** are inserted in between. The locking might fail on one of the later
7172** transitions leaving the lock state different from what it started but
7173** still short of its goal. The following chart shows the allowed
7174** transitions and the inserted intermediate states:
7175**
7176** UNLOCKED -> SHARED
7177** SHARED -> RESERVED
7178** SHARED -> (PENDING) -> EXCLUSIVE
7179** RESERVED -> (PENDING) -> EXCLUSIVE
7180** PENDING -> EXCLUSIVE
7181**
7182** This routine will only increase a lock. Use the sqlite3OsUnlock()
7183** routine to lower a locking level.
7184*/
drh308c2a52010-05-14 11:30:18 +00007185static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007186 unixFile *pFile = (unixFile*)id;
7187 int rc = proxyTakeConch(pFile);
7188 if( rc==SQLITE_OK ){
7189 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007190 if( pCtx->conchHeld>0 ){
7191 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007192 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7193 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007194 }else{
7195 /* conchHeld < 0 is lockless */
7196 }
drh715ff302008-12-03 22:32:44 +00007197 }
7198 return rc;
7199}
7200
7201
7202/*
drh308c2a52010-05-14 11:30:18 +00007203** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007204** must be either NO_LOCK or SHARED_LOCK.
7205**
7206** If the locking level of the file descriptor is already at or below
7207** the requested locking level, this routine is a no-op.
7208*/
drh308c2a52010-05-14 11:30:18 +00007209static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007210 unixFile *pFile = (unixFile*)id;
7211 int rc = proxyTakeConch(pFile);
7212 if( rc==SQLITE_OK ){
7213 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007214 if( pCtx->conchHeld>0 ){
7215 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007216 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7217 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007218 }else{
7219 /* conchHeld < 0 is lockless */
7220 }
drh715ff302008-12-03 22:32:44 +00007221 }
7222 return rc;
7223}
7224
7225/*
7226** Close a file that uses proxy locks.
7227*/
7228static int proxyClose(sqlite3_file *id) {
7229 if( id ){
7230 unixFile *pFile = (unixFile*)id;
7231 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7232 unixFile *lockProxy = pCtx->lockProxy;
7233 unixFile *conchFile = pCtx->conchFile;
7234 int rc = SQLITE_OK;
7235
7236 if( lockProxy ){
7237 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7238 if( rc ) return rc;
7239 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7240 if( rc ) return rc;
7241 sqlite3_free(lockProxy);
7242 pCtx->lockProxy = 0;
7243 }
7244 if( conchFile ){
7245 if( pCtx->conchHeld ){
7246 rc = proxyReleaseConch(pFile);
7247 if( rc ) return rc;
7248 }
7249 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7250 if( rc ) return rc;
7251 sqlite3_free(conchFile);
7252 }
drhd56b1212010-08-11 06:14:15 +00007253 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007254 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007255 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007256 /* restore the original locking context and pMethod then close it */
7257 pFile->lockingContext = pCtx->oldLockingContext;
7258 pFile->pMethod = pCtx->pOldMethod;
7259 sqlite3_free(pCtx);
7260 return pFile->pMethod->xClose(id);
7261 }
7262 return SQLITE_OK;
7263}
7264
7265
7266
drhd2cb50b2009-01-09 21:41:17 +00007267#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007268/*
7269** The proxy locking style is intended for use with AFP filesystems.
7270** And since AFP is only supported on MacOSX, the proxy locking is also
7271** restricted to MacOSX.
7272**
7273**
7274******************* End of the proxy lock implementation **********************
7275******************************************************************************/
7276
drh734c9862008-11-28 15:37:20 +00007277/*
danielk1977e339d652008-06-28 11:23:00 +00007278** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007279**
7280** This routine registers all VFS implementations for unix-like operating
7281** systems. This routine, and the sqlite3_os_end() routine that follows,
7282** should be the only routines in this file that are visible from other
7283** files.
drh6b9d6dd2008-12-03 19:34:47 +00007284**
7285** This routine is called once during SQLite initialization and by a
7286** single thread. The memory allocation and mutex subsystems have not
7287** necessarily been initialized when this routine is called, and so they
7288** should not be used.
drh153c62c2007-08-24 03:51:33 +00007289*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007290int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007291 /*
7292 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007293 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7294 ** to the "finder" function. (pAppData is a pointer to a pointer because
7295 ** silly C90 rules prohibit a void* from being cast to a function pointer
7296 ** and so we have to go through the intermediate pointer to avoid problems
7297 ** when compiling with -pedantic-errors on GCC.)
7298 **
7299 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007300 ** finder-function. The finder-function returns a pointer to the
7301 ** sqlite_io_methods object that implements the desired locking
7302 ** behaviors. See the division above that contains the IOMETHODS
7303 ** macro for addition information on finder-functions.
7304 **
7305 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7306 ** object. But the "autolockIoFinder" available on MacOSX does a little
7307 ** more than that; it looks at the filesystem type that hosts the
7308 ** database file and tries to choose an locking method appropriate for
7309 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007310 */
drh7708e972008-11-29 00:56:52 +00007311 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007312 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007313 sizeof(unixFile), /* szOsFile */ \
7314 MAX_PATHNAME, /* mxPathname */ \
7315 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007316 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007317 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007318 unixOpen, /* xOpen */ \
7319 unixDelete, /* xDelete */ \
7320 unixAccess, /* xAccess */ \
7321 unixFullPathname, /* xFullPathname */ \
7322 unixDlOpen, /* xDlOpen */ \
7323 unixDlError, /* xDlError */ \
7324 unixDlSym, /* xDlSym */ \
7325 unixDlClose, /* xDlClose */ \
7326 unixRandomness, /* xRandomness */ \
7327 unixSleep, /* xSleep */ \
7328 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007329 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007330 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007331 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007332 unixGetSystemCall, /* xGetSystemCall */ \
7333 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007334 }
7335
drh6b9d6dd2008-12-03 19:34:47 +00007336 /*
7337 ** All default VFSes for unix are contained in the following array.
7338 **
7339 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7340 ** by the SQLite core when the VFS is registered. So the following
7341 ** array cannot be const.
7342 */
danielk1977e339d652008-06-28 11:23:00 +00007343 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007344#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007345 UNIXVFS("unix", autolockIoFinder ),
7346#else
7347 UNIXVFS("unix", posixIoFinder ),
7348#endif
7349 UNIXVFS("unix-none", nolockIoFinder ),
7350 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007351 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007352#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007353 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007354#endif
7355#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007356 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007357#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007358 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007359#endif
chw78a13182009-04-07 05:35:03 +00007360#endif
drhd2cb50b2009-01-09 21:41:17 +00007361#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007362 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007363 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007364 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007365#endif
drh153c62c2007-08-24 03:51:33 +00007366 };
drh6b9d6dd2008-12-03 19:34:47 +00007367 unsigned int i; /* Loop counter */
7368
drh2aa5a002011-04-13 13:42:25 +00007369 /* Double-check that the aSyscall[] array has been constructed
7370 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007371 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007372
drh6b9d6dd2008-12-03 19:34:47 +00007373 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007374 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007375 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007376 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007377 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007378}
danielk1977e339d652008-06-28 11:23:00 +00007379
7380/*
drh6b9d6dd2008-12-03 19:34:47 +00007381** Shutdown the operating system interface.
7382**
7383** Some operating systems might need to do some cleanup in this routine,
7384** to release dynamically allocated objects. But not on unix.
7385** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007386*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007387int sqlite3_os_end(void){
7388 return SQLITE_OK;
7389}
drhdce8bdb2007-08-16 13:01:44 +00007390
danielk197729bafea2008-06-26 10:41:19 +00007391#endif /* SQLITE_OS_UNIX */