blob: 152bf9a113b7d0b22efc704720a8fcf90f99564c [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +0000122#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
drh1da88f02011-12-17 16:09:16 +0000125
danielk1977e339d652008-06-28 11:23:00 +0000126
drh40bbb0a2008-09-23 10:23:26 +0000127#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000129# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <semaphore.h>
131# include <limits.h>
132# else
drh9b35ea62008-11-29 02:20:26 +0000133# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000135# endif
drhbfe66312006-10-03 17:40:40 +0000136#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000137
drhf8b4d8c2010-03-05 13:53:22 +0000138#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000139# include <sys/mount.h>
140#endif
141
drhdbe4b882011-06-20 18:00:17 +0000142#ifdef HAVE_UTIME
143# include <utime.h>
144#endif
145
drh9cbe6352005-11-29 03:13:21 +0000146/*
drh7ed97b92010-01-20 13:07:21 +0000147** Allowed values of unixFile.fsFlags
148*/
149#define SQLITE_FSFLAGS_IS_MSDOS 0x1
150
151/*
drhf1a221e2006-01-15 17:27:17 +0000152** If we are to be thread-safe, include the pthreads header and define
153** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000154*/
drhd677b3d2007-08-20 22:48:41 +0000155#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000156# include <pthread.h>
157# define SQLITE_UNIX_THREADS 1
158#endif
159
160/*
161** Default permissions when creating a new file
162*/
163#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
164# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
165#endif
166
danielk1977b4b47412007-08-17 15:53:36 +0000167/*
drh5adc60b2012-04-14 13:25:11 +0000168** Default permissions when creating auto proxy dir
169*/
aswiftaebf4132008-11-21 00:10:35 +0000170#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
171# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
172#endif
173
174/*
danielk1977b4b47412007-08-17 15:53:36 +0000175** Maximum supported path-length.
176*/
177#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000178
drh734c9862008-11-28 15:37:20 +0000179/*
drh734c9862008-11-28 15:37:20 +0000180** Only set the lastErrno if the error code is a real error and not
181** a normal expected return code of SQLITE_BUSY or SQLITE_OK
182*/
183#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
184
drhd91c68f2010-05-14 14:52:25 +0000185/* Forward references */
186typedef struct unixShm unixShm; /* Connection shared memory */
187typedef struct unixShmNode unixShmNode; /* Shared memory instance */
188typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
189typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000190
191/*
dane946c392009-08-22 11:39:46 +0000192** Sometimes, after a file handle is closed by SQLite, the file descriptor
193** cannot be closed immediately. In these cases, instances of the following
194** structure are used to store the file descriptor while waiting for an
195** opportunity to either close or reuse it.
196*/
dane946c392009-08-22 11:39:46 +0000197struct UnixUnusedFd {
198 int fd; /* File descriptor to close */
199 int flags; /* Flags this file descriptor was opened with */
200 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
201};
202
203/*
drh9b35ea62008-11-29 02:20:26 +0000204** The unixFile structure is subclass of sqlite3_file specific to the unix
205** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000206*/
drh054889e2005-11-30 03:20:31 +0000207typedef struct unixFile unixFile;
208struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000209 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000210 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000211 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000212 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000213 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000214 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000215 int lastErrno; /* The unix errno from last I/O error */
216 void *lockingContext; /* Locking style specific state */
217 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000218 const char *zPath; /* Name of the file */
219 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000220 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh0d0614b2013-03-25 23:09:28 +0000221 int nFetchOut; /* Number of outstanding xFetch refs */
222 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000223 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
224 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000225 void *pMapRegion; /* Memory mapped region */
drh537dddf2012-10-26 13:46:24 +0000226#ifdef __QNXNTO__
227 int sectorSize; /* Device sector size */
228 int deviceCharacteristics; /* Precomputed device characteristics */
229#endif
drh08c6d442009-02-09 17:34:07 +0000230#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000231 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000232#endif
drh7ed97b92010-01-20 13:07:21 +0000233#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000234 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000235#endif
236#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000237 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000238#endif
drhd3d8c042012-05-29 17:02:40 +0000239#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000240 /* The next group of variables are used to track whether or not the
241 ** transaction counter in bytes 24-27 of database files are updated
242 ** whenever any part of the database changes. An assertion fault will
243 ** occur if a file is updated without also updating the transaction
244 ** counter. This test is made to avoid new problems similar to the
245 ** one described by ticket #3584.
246 */
247 unsigned char transCntrChng; /* True if the transaction counter changed */
248 unsigned char dbUpdate; /* True if any part of database file changed */
249 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000250
drh8f941bc2009-01-14 23:03:40 +0000251#endif
danf23da962013-03-23 21:00:41 +0000252
danielk1977967a4a12007-08-20 14:23:44 +0000253#ifdef SQLITE_TEST
254 /* In test mode, increase the size of this structure a bit so that
255 ** it is larger than the struct CrashFile defined in test6.c.
256 */
257 char aPadding[32];
258#endif
drh9cbe6352005-11-29 03:13:21 +0000259};
260
drh0ccebe72005-06-07 22:22:50 +0000261/*
drha7e61d82011-03-12 17:02:57 +0000262** Allowed values for the unixFile.ctrlFlags bitmask:
263*/
drhf0b190d2011-07-26 16:03:07 +0000264#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
265#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
266#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000267#ifndef SQLITE_DISABLE_DIRSYNC
268# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
269#else
270# define UNIXFILE_DIRSYNC 0x00
271#endif
drhcb15f352011-12-23 01:04:17 +0000272#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000273#define UNIXFILE_DELETE 0x20 /* Delete on close */
274#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
275#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhfbc7e882013-04-11 01:16:15 +0000276#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
drha7e61d82011-03-12 17:02:57 +0000277
278/*
drh198bf392006-01-06 21:52:49 +0000279** Include code that is common to all os_*.c files
280*/
281#include "os_common.h"
282
283/*
drh0ccebe72005-06-07 22:22:50 +0000284** Define various macros that are missing from some systems.
285*/
drhbbd42a62004-05-22 17:41:58 +0000286#ifndef O_LARGEFILE
287# define O_LARGEFILE 0
288#endif
289#ifdef SQLITE_DISABLE_LFS
290# undef O_LARGEFILE
291# define O_LARGEFILE 0
292#endif
293#ifndef O_NOFOLLOW
294# define O_NOFOLLOW 0
295#endif
296#ifndef O_BINARY
297# define O_BINARY 0
298#endif
299
300/*
drh2b4b5962005-06-15 17:47:55 +0000301** The threadid macro resolves to the thread-id or to 0. Used for
302** testing and debugging only.
303*/
drhd677b3d2007-08-20 22:48:41 +0000304#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000305#define threadid pthread_self()
306#else
307#define threadid 0
308#endif
309
drh99ab3b12011-03-02 15:09:07 +0000310/*
dane6ecd662013-04-01 17:56:59 +0000311** HAVE_MREMAP defaults to true on Linux and false everywhere else.
312*/
313#if !defined(HAVE_MREMAP)
314# if defined(__linux__) && defined(_GNU_SOURCE)
315# define HAVE_MREMAP 1
316# else
317# define HAVE_MREMAP 0
318# endif
319#endif
320
321/*
drh9a3baf12011-04-25 18:01:27 +0000322** Different Unix systems declare open() in different ways. Same use
323** open(const char*,int,mode_t). Others use open(const char*,int,...).
324** The difference is important when using a pointer to the function.
325**
326** The safest way to deal with the problem is to always use this wrapper
327** which always has the same well-defined interface.
328*/
329static int posixOpen(const char *zFile, int flags, int mode){
330 return open(zFile, flags, mode);
331}
332
drhed466822012-05-31 13:10:49 +0000333/*
334** On some systems, calls to fchown() will trigger a message in a security
335** log if they come from non-root processes. So avoid calling fchown() if
336** we are not running as root.
337*/
338static int posixFchown(int fd, uid_t uid, gid_t gid){
339 return geteuid() ? 0 : fchown(fd,uid,gid);
340}
341
drh90315a22011-08-10 01:52:12 +0000342/* Forward reference */
343static int openDirectory(const char*, int*);
344
drh9a3baf12011-04-25 18:01:27 +0000345/*
drh99ab3b12011-03-02 15:09:07 +0000346** Many system calls are accessed through pointer-to-functions so that
347** they may be overridden at runtime to facilitate fault injection during
348** testing and sandboxing. The following array holds the names and pointers
349** to all overrideable system calls.
350*/
351static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000352 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000353 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
354 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000355} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000356 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
357#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000358
drh58ad5802011-03-23 22:02:23 +0000359 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000360#define osClose ((int(*)(int))aSyscall[1].pCurrent)
361
drh58ad5802011-03-23 22:02:23 +0000362 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000363#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
364
drh58ad5802011-03-23 22:02:23 +0000365 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000366#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
367
drh58ad5802011-03-23 22:02:23 +0000368 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000369#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
370
371/*
372** The DJGPP compiler environment looks mostly like Unix, but it
373** lacks the fcntl() system call. So redefine fcntl() to be something
374** that always succeeds. This means that locking does not occur under
375** DJGPP. But it is DOS - what did you expect?
376*/
377#ifdef __DJGPP__
378 { "fstat", 0, 0 },
379#define osFstat(a,b,c) 0
380#else
drh58ad5802011-03-23 22:02:23 +0000381 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000382#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
383#endif
384
drh58ad5802011-03-23 22:02:23 +0000385 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000386#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
387
drh58ad5802011-03-23 22:02:23 +0000388 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000389#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000390
drh58ad5802011-03-23 22:02:23 +0000391 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000392#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
393
drhd4a80312011-04-15 14:33:20 +0000394#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000395 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000396#else
drh58ad5802011-03-23 22:02:23 +0000397 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000398#endif
399#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
400
401#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000402 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000403#else
drh58ad5802011-03-23 22:02:23 +0000404 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000405#endif
406#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
407
drh58ad5802011-03-23 22:02:23 +0000408 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000409#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
410
drhd4a80312011-04-15 14:33:20 +0000411#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000412 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000413#else
drh58ad5802011-03-23 22:02:23 +0000414 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000415#endif
416#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
417 aSyscall[12].pCurrent)
418
419#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000420 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000421#else
drh58ad5802011-03-23 22:02:23 +0000422 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000423#endif
424#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
425 aSyscall[13].pCurrent)
426
drh58ad5802011-03-23 22:02:23 +0000427 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000428#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000429
430#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000431 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000432#else
drh58ad5802011-03-23 22:02:23 +0000433 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000434#endif
dan0fd7d862011-03-29 10:04:23 +0000435#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000436
drh036ac7f2011-08-08 23:18:05 +0000437 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
438#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
439
drh90315a22011-08-10 01:52:12 +0000440 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
441#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
442
drh9ef6bc42011-11-04 02:24:02 +0000443 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
444#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
445
446 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
447#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
448
drhed466822012-05-31 13:10:49 +0000449 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000450#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000451
dan893c0ff2013-03-25 19:05:07 +0000452 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
453#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
454
drhd1ab8062013-03-25 20:50:25 +0000455 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
456#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
457
dane6ecd662013-04-01 17:56:59 +0000458#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000459 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
460#else
461 { "mremap", (sqlite3_syscall_ptr)0, 0 },
462#endif
463#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
464
drhe562be52011-03-02 18:01:10 +0000465}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000466
467/*
468** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000469** "unix" VFSes. Return SQLITE_OK opon successfully updating the
470** system call pointer, or SQLITE_NOTFOUND if there is no configurable
471** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000472*/
473static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000474 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
475 const char *zName, /* Name of system call to override */
476 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000477){
drh58ad5802011-03-23 22:02:23 +0000478 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000479 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000480
481 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000482 if( zName==0 ){
483 /* If no zName is given, restore all system calls to their default
484 ** settings and return NULL
485 */
dan51438a72011-04-02 17:00:47 +0000486 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000487 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
488 if( aSyscall[i].pDefault ){
489 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000490 }
491 }
492 }else{
493 /* If zName is specified, operate on only the one system call
494 ** specified.
495 */
496 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
497 if( strcmp(zName, aSyscall[i].zName)==0 ){
498 if( aSyscall[i].pDefault==0 ){
499 aSyscall[i].pDefault = aSyscall[i].pCurrent;
500 }
drh1df30962011-03-02 19:06:42 +0000501 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000502 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
503 aSyscall[i].pCurrent = pNewFunc;
504 break;
505 }
506 }
507 }
508 return rc;
509}
510
drh1df30962011-03-02 19:06:42 +0000511/*
512** Return the value of a system call. Return NULL if zName is not a
513** recognized system call name. NULL is also returned if the system call
514** is currently undefined.
515*/
drh58ad5802011-03-23 22:02:23 +0000516static sqlite3_syscall_ptr unixGetSystemCall(
517 sqlite3_vfs *pNotUsed,
518 const char *zName
519){
520 unsigned int i;
521
522 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000523 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
524 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
525 }
526 return 0;
527}
528
529/*
530** Return the name of the first system call after zName. If zName==NULL
531** then return the name of the first system call. Return NULL if zName
532** is the last system call or if zName is not the name of a valid
533** system call.
534*/
535static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000536 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000537
538 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000539 if( zName ){
540 for(i=0; i<ArraySize(aSyscall)-1; i++){
541 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000542 }
543 }
dan0fd7d862011-03-29 10:04:23 +0000544 for(i++; i<ArraySize(aSyscall); i++){
545 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000546 }
547 return 0;
548}
549
drhad4f1e52011-03-04 15:43:57 +0000550/*
drh8c815d12012-02-13 20:16:37 +0000551** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000552** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000553**
554** If the file creation mode "m" is 0 then set it to the default for
555** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
556** 0644) as modified by the system umask. If m is not 0, then
557** make the file creation mode be exactly m ignoring the umask.
558**
559** The m parameter will be non-zero only when creating -wal, -journal,
560** and -shm files. We want those files to have *exactly* the same
561** permissions as their original database, unadulterated by the umask.
562** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
563** transaction crashes and leaves behind hot journals, then any
564** process that is able to write to the database will also be able to
565** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000566*/
drh8c815d12012-02-13 20:16:37 +0000567static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000568 int fd;
drhe1186ab2013-01-04 20:45:13 +0000569 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5adc60b2012-04-14 13:25:11 +0000570 do{
571#if defined(O_CLOEXEC)
572 fd = osOpen(z,f|O_CLOEXEC,m2);
573#else
574 fd = osOpen(z,f,m2);
575#endif
576 }while( fd<0 && errno==EINTR );
drhe1186ab2013-01-04 20:45:13 +0000577 if( fd>=0 ){
578 if( m!=0 ){
579 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000580 if( osFstat(fd, &statbuf)==0
581 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000582 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000583 ){
drhe1186ab2013-01-04 20:45:13 +0000584 osFchmod(fd, m);
585 }
586 }
drh5adc60b2012-04-14 13:25:11 +0000587#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000588 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000589#endif
drhe1186ab2013-01-04 20:45:13 +0000590 }
drh5adc60b2012-04-14 13:25:11 +0000591 return fd;
drhad4f1e52011-03-04 15:43:57 +0000592}
danielk197713adf8a2004-06-03 16:08:41 +0000593
drh107886a2008-11-21 22:21:50 +0000594/*
dan9359c7b2009-08-21 08:29:10 +0000595** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000596** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000597** vxworksFileId objects used by this file, all of which may be
598** shared by multiple threads.
599**
600** Function unixMutexHeld() is used to assert() that the global mutex
601** is held when required. This function is only used as part of assert()
602** statements. e.g.
603**
604** unixEnterMutex()
605** assert( unixMutexHeld() );
606** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000607*/
608static void unixEnterMutex(void){
609 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
610}
611static void unixLeaveMutex(void){
612 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
613}
dan9359c7b2009-08-21 08:29:10 +0000614#ifdef SQLITE_DEBUG
615static int unixMutexHeld(void) {
616 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
617}
618#endif
drh107886a2008-11-21 22:21:50 +0000619
drh734c9862008-11-28 15:37:20 +0000620
drh30ddce62011-10-15 00:16:30 +0000621#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000622/*
623** Helper function for printing out trace information from debugging
624** binaries. This returns the string represetation of the supplied
625** integer lock-type.
626*/
drh308c2a52010-05-14 11:30:18 +0000627static const char *azFileLock(int eFileLock){
628 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000629 case NO_LOCK: return "NONE";
630 case SHARED_LOCK: return "SHARED";
631 case RESERVED_LOCK: return "RESERVED";
632 case PENDING_LOCK: return "PENDING";
633 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000634 }
635 return "ERROR";
636}
637#endif
638
639#ifdef SQLITE_LOCK_TRACE
640/*
641** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000642**
drh734c9862008-11-28 15:37:20 +0000643** This routine is used for troubleshooting locks on multithreaded
644** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
645** command-line option on the compiler. This code is normally
646** turned off.
647*/
648static int lockTrace(int fd, int op, struct flock *p){
649 char *zOpName, *zType;
650 int s;
651 int savedErrno;
652 if( op==F_GETLK ){
653 zOpName = "GETLK";
654 }else if( op==F_SETLK ){
655 zOpName = "SETLK";
656 }else{
drh99ab3b12011-03-02 15:09:07 +0000657 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000658 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
659 return s;
660 }
661 if( p->l_type==F_RDLCK ){
662 zType = "RDLCK";
663 }else if( p->l_type==F_WRLCK ){
664 zType = "WRLCK";
665 }else if( p->l_type==F_UNLCK ){
666 zType = "UNLCK";
667 }else{
668 assert( 0 );
669 }
670 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000671 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000672 savedErrno = errno;
673 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
674 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
675 (int)p->l_pid, s);
676 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
677 struct flock l2;
678 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000679 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000680 if( l2.l_type==F_RDLCK ){
681 zType = "RDLCK";
682 }else if( l2.l_type==F_WRLCK ){
683 zType = "WRLCK";
684 }else if( l2.l_type==F_UNLCK ){
685 zType = "UNLCK";
686 }else{
687 assert( 0 );
688 }
689 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
690 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
691 }
692 errno = savedErrno;
693 return s;
694}
drh99ab3b12011-03-02 15:09:07 +0000695#undef osFcntl
696#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000697#endif /* SQLITE_LOCK_TRACE */
698
drhff812312011-02-23 13:33:46 +0000699/*
700** Retry ftruncate() calls that fail due to EINTR
701*/
drhff812312011-02-23 13:33:46 +0000702static int robust_ftruncate(int h, sqlite3_int64 sz){
703 int rc;
drh99ab3b12011-03-02 15:09:07 +0000704 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000705 return rc;
706}
drh734c9862008-11-28 15:37:20 +0000707
708/*
709** This routine translates a standard POSIX errno code into something
710** useful to the clients of the sqlite3 functions. Specifically, it is
711** intended to translate a variety of "try again" errors into SQLITE_BUSY
712** and a variety of "please close the file descriptor NOW" errors into
713** SQLITE_IOERR
714**
715** Errors during initialization of locks, or file system support for locks,
716** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
717*/
718static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
719 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000720#if 0
721 /* At one point this code was not commented out. In theory, this branch
722 ** should never be hit, as this function should only be called after
723 ** a locking-related function (i.e. fcntl()) has returned non-zero with
724 ** the value of errno as the first argument. Since a system call has failed,
725 ** errno should be non-zero.
726 **
727 ** Despite this, if errno really is zero, we still don't want to return
728 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
729 ** propagated back to the caller. Commenting this branch out means errno==0
730 ** will be handled by the "default:" case below.
731 */
drh734c9862008-11-28 15:37:20 +0000732 case 0:
733 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000734#endif
735
drh734c9862008-11-28 15:37:20 +0000736 case EAGAIN:
737 case ETIMEDOUT:
738 case EBUSY:
739 case EINTR:
740 case ENOLCK:
741 /* random NFS retry error, unless during file system support
742 * introspection, in which it actually means what it says */
743 return SQLITE_BUSY;
744
745 case EACCES:
746 /* EACCES is like EAGAIN during locking operations, but not any other time*/
747 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000748 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
749 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
750 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000751 return SQLITE_BUSY;
752 }
753 /* else fall through */
754 case EPERM:
755 return SQLITE_PERM;
756
danea83bc62011-04-01 11:56:32 +0000757 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
758 ** this module never makes such a call. And the code in SQLite itself
759 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
760 ** this case is also commented out. If the system does set errno to EDEADLK,
761 ** the default SQLITE_IOERR_XXX code will be returned. */
762#if 0
drh734c9862008-11-28 15:37:20 +0000763 case EDEADLK:
764 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000765#endif
drh734c9862008-11-28 15:37:20 +0000766
767#if EOPNOTSUPP!=ENOTSUP
768 case EOPNOTSUPP:
769 /* something went terribly awry, unless during file system support
770 * introspection, in which it actually means what it says */
771#endif
772#ifdef ENOTSUP
773 case ENOTSUP:
774 /* invalid fd, unless during file system support introspection, in which
775 * it actually means what it says */
776#endif
777 case EIO:
778 case EBADF:
779 case EINVAL:
780 case ENOTCONN:
781 case ENODEV:
782 case ENXIO:
783 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000784#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000785 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000786#endif
drh734c9862008-11-28 15:37:20 +0000787 case ENOSYS:
788 /* these should force the client to close the file and reconnect */
789
790 default:
791 return sqliteIOErr;
792 }
793}
794
795
drh734c9862008-11-28 15:37:20 +0000796/******************************************************************************
797****************** Begin Unique File ID Utility Used By VxWorks ***************
798**
799** On most versions of unix, we can get a unique ID for a file by concatenating
800** the device number and the inode number. But this does not work on VxWorks.
801** On VxWorks, a unique file id must be based on the canonical filename.
802**
803** A pointer to an instance of the following structure can be used as a
804** unique file ID in VxWorks. Each instance of this structure contains
805** a copy of the canonical filename. There is also a reference count.
806** The structure is reclaimed when the number of pointers to it drops to
807** zero.
808**
809** There are never very many files open at one time and lookups are not
810** a performance-critical path, so it is sufficient to put these
811** structures on a linked list.
812*/
813struct vxworksFileId {
814 struct vxworksFileId *pNext; /* Next in a list of them all */
815 int nRef; /* Number of references to this one */
816 int nName; /* Length of the zCanonicalName[] string */
817 char *zCanonicalName; /* Canonical filename */
818};
819
820#if OS_VXWORKS
821/*
drh9b35ea62008-11-29 02:20:26 +0000822** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000823** variable:
824*/
825static struct vxworksFileId *vxworksFileList = 0;
826
827/*
828** Simplify a filename into its canonical form
829** by making the following changes:
830**
831** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000832** * convert /./ into just /
833** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000834**
835** Changes are made in-place. Return the new name length.
836**
837** The original filename is in z[0..n-1]. Return the number of
838** characters in the simplified name.
839*/
840static int vxworksSimplifyName(char *z, int n){
841 int i, j;
842 while( n>1 && z[n-1]=='/' ){ n--; }
843 for(i=j=0; i<n; i++){
844 if( z[i]=='/' ){
845 if( z[i+1]=='/' ) continue;
846 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
847 i += 1;
848 continue;
849 }
850 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
851 while( j>0 && z[j-1]!='/' ){ j--; }
852 if( j>0 ){ j--; }
853 i += 2;
854 continue;
855 }
856 }
857 z[j++] = z[i];
858 }
859 z[j] = 0;
860 return j;
861}
862
863/*
864** Find a unique file ID for the given absolute pathname. Return
865** a pointer to the vxworksFileId object. This pointer is the unique
866** file ID.
867**
868** The nRef field of the vxworksFileId object is incremented before
869** the object is returned. A new vxworksFileId object is created
870** and added to the global list if necessary.
871**
872** If a memory allocation error occurs, return NULL.
873*/
874static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
875 struct vxworksFileId *pNew; /* search key and new file ID */
876 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
877 int n; /* Length of zAbsoluteName string */
878
879 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000880 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000881 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
882 if( pNew==0 ) return 0;
883 pNew->zCanonicalName = (char*)&pNew[1];
884 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
885 n = vxworksSimplifyName(pNew->zCanonicalName, n);
886
887 /* Search for an existing entry that matching the canonical name.
888 ** If found, increment the reference count and return a pointer to
889 ** the existing file ID.
890 */
891 unixEnterMutex();
892 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
893 if( pCandidate->nName==n
894 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
895 ){
896 sqlite3_free(pNew);
897 pCandidate->nRef++;
898 unixLeaveMutex();
899 return pCandidate;
900 }
901 }
902
903 /* No match was found. We will make a new file ID */
904 pNew->nRef = 1;
905 pNew->nName = n;
906 pNew->pNext = vxworksFileList;
907 vxworksFileList = pNew;
908 unixLeaveMutex();
909 return pNew;
910}
911
912/*
913** Decrement the reference count on a vxworksFileId object. Free
914** the object when the reference count reaches zero.
915*/
916static void vxworksReleaseFileId(struct vxworksFileId *pId){
917 unixEnterMutex();
918 assert( pId->nRef>0 );
919 pId->nRef--;
920 if( pId->nRef==0 ){
921 struct vxworksFileId **pp;
922 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
923 assert( *pp==pId );
924 *pp = pId->pNext;
925 sqlite3_free(pId);
926 }
927 unixLeaveMutex();
928}
929#endif /* OS_VXWORKS */
930/*************** End of Unique File ID Utility Used By VxWorks ****************
931******************************************************************************/
932
933
934/******************************************************************************
935*************************** Posix Advisory Locking ****************************
936**
drh9b35ea62008-11-29 02:20:26 +0000937** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000938** section 6.5.2.2 lines 483 through 490 specify that when a process
939** sets or clears a lock, that operation overrides any prior locks set
940** by the same process. It does not explicitly say so, but this implies
941** that it overrides locks set by the same process using a different
942** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000943**
944** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000945** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
946**
947** Suppose ./file1 and ./file2 are really the same file (because
948** one is a hard or symbolic link to the other) then if you set
949** an exclusive lock on fd1, then try to get an exclusive lock
950** on fd2, it works. I would have expected the second lock to
951** fail since there was already a lock on the file due to fd1.
952** But not so. Since both locks came from the same process, the
953** second overrides the first, even though they were on different
954** file descriptors opened on different file names.
955**
drh734c9862008-11-28 15:37:20 +0000956** This means that we cannot use POSIX locks to synchronize file access
957** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000958** to synchronize access for threads in separate processes, but not
959** threads within the same process.
960**
961** To work around the problem, SQLite has to manage file locks internally
962** on its own. Whenever a new database is opened, we have to find the
963** specific inode of the database file (the inode is determined by the
964** st_dev and st_ino fields of the stat structure that fstat() fills in)
965** and check for locks already existing on that inode. When locks are
966** created or removed, we have to look at our own internal record of the
967** locks to see if another thread has previously set a lock on that same
968** inode.
969**
drh9b35ea62008-11-29 02:20:26 +0000970** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
971** For VxWorks, we have to use the alternative unique ID system based on
972** canonical filename and implemented in the previous division.)
973**
danielk1977ad94b582007-08-20 06:44:22 +0000974** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000975** descriptor. It is now a structure that holds the integer file
976** descriptor and a pointer to a structure that describes the internal
977** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000978** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000979** point to the same locking structure. The locking structure keeps
980** a reference count (so we will know when to delete it) and a "cnt"
981** field that tells us its internal lock status. cnt==0 means the
982** file is unlocked. cnt==-1 means the file has an exclusive lock.
983** cnt>0 means there are cnt shared locks on the file.
984**
985** Any attempt to lock or unlock a file first checks the locking
986** structure. The fcntl() system call is only invoked to set a
987** POSIX lock if the internal lock structure transitions between
988** a locked and an unlocked state.
989**
drh734c9862008-11-28 15:37:20 +0000990** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000991**
992** If you close a file descriptor that points to a file that has locks,
993** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000994** released. To work around this problem, each unixInodeInfo object
995** maintains a count of the number of pending locks on tha inode.
996** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000997** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000998** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000999** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001000** be closed and that list is walked (and cleared) when the last lock
1001** clears.
1002**
drh9b35ea62008-11-29 02:20:26 +00001003** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001004**
drh9b35ea62008-11-29 02:20:26 +00001005** Many older versions of linux use the LinuxThreads library which is
1006** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001007** A cannot be modified or overridden by a different thread B.
1008** Only thread A can modify the lock. Locking behavior is correct
1009** if the appliation uses the newer Native Posix Thread Library (NPTL)
1010** on linux - with NPTL a lock created by thread A can override locks
1011** in thread B. But there is no way to know at compile-time which
1012** threading library is being used. So there is no way to know at
1013** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001014** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001015** current process.
drh5fdae772004-06-29 03:29:00 +00001016**
drh8af6c222010-05-14 12:43:01 +00001017** SQLite used to support LinuxThreads. But support for LinuxThreads
1018** was dropped beginning with version 3.7.0. SQLite will still work with
1019** LinuxThreads provided that (1) there is no more than one connection
1020** per database file in the same process and (2) database connections
1021** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001022*/
1023
1024/*
1025** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001026** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001027*/
1028struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001029 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001030#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001031 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001032#else
drh107886a2008-11-21 22:21:50 +00001033 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001034#endif
1035};
1036
1037/*
drhbbd42a62004-05-22 17:41:58 +00001038** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001039** inode. Or, on LinuxThreads, there is one of these structures for
1040** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001041**
danielk1977ad94b582007-08-20 06:44:22 +00001042** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001043** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001044** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001045*/
drh8af6c222010-05-14 12:43:01 +00001046struct unixInodeInfo {
1047 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001048 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001049 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1050 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001051 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001052 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1053 int nLock; /* Number of outstanding file locks */
1054 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1055 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1056 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001057#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001058 unsigned long long sharedByte; /* for AFP simulated shared lock */
1059#endif
drh6c7d5c52008-11-21 20:32:33 +00001060#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001061 sem_t *pSem; /* Named POSIX semaphore */
1062 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001063#endif
drhbbd42a62004-05-22 17:41:58 +00001064};
1065
drhda0e7682008-07-30 15:27:54 +00001066/*
drh8af6c222010-05-14 12:43:01 +00001067** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001068*/
drhd91c68f2010-05-14 14:52:25 +00001069static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001070
drh5fdae772004-06-29 03:29:00 +00001071/*
dane18d4952011-02-21 11:46:24 +00001072**
1073** This function - unixLogError_x(), is only ever called via the macro
1074** unixLogError().
1075**
1076** It is invoked after an error occurs in an OS function and errno has been
1077** set. It logs a message using sqlite3_log() containing the current value of
1078** errno and, if possible, the human-readable equivalent from strerror() or
1079** strerror_r().
1080**
1081** The first argument passed to the macro should be the error code that
1082** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1083** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001084** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001085** if any.
1086*/
drh0e9365c2011-03-02 02:08:13 +00001087#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1088static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001089 int errcode, /* SQLite error code */
1090 const char *zFunc, /* Name of OS function that failed */
1091 const char *zPath, /* File path associated with error */
1092 int iLine /* Source line number where error occurred */
1093){
1094 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001095 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001096
1097 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1098 ** the strerror() function to obtain the human-readable error message
1099 ** equivalent to errno. Otherwise, use strerror_r().
1100 */
1101#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1102 char aErr[80];
1103 memset(aErr, 0, sizeof(aErr));
1104 zErr = aErr;
1105
1106 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001107 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001108 ** returns a pointer to a buffer containing the error message. That pointer
1109 ** may point to aErr[], or it may point to some static storage somewhere.
1110 ** Otherwise, assume that the system provides the POSIX version of
1111 ** strerror_r(), which always writes an error message into aErr[].
1112 **
1113 ** If the code incorrectly assumes that it is the POSIX version that is
1114 ** available, the error message will often be an empty string. Not a
1115 ** huge problem. Incorrectly concluding that the GNU version is available
1116 ** could lead to a segfault though.
1117 */
1118#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1119 zErr =
1120# endif
drh0e9365c2011-03-02 02:08:13 +00001121 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001122
1123#elif SQLITE_THREADSAFE
1124 /* This is a threadsafe build, but strerror_r() is not available. */
1125 zErr = "";
1126#else
1127 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001128 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001129#endif
1130
drh0e9365c2011-03-02 02:08:13 +00001131 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001132 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001133 "os_unix.c:%d: (%d) %s(%s) - %s",
1134 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001135 );
1136
1137 return errcode;
1138}
1139
drh0e9365c2011-03-02 02:08:13 +00001140/*
1141** Close a file descriptor.
1142**
1143** We assume that close() almost always works, since it is only in a
1144** very sick application or on a very sick platform that it might fail.
1145** If it does fail, simply leak the file descriptor, but do log the
1146** error.
1147**
1148** Note that it is not safe to retry close() after EINTR since the
1149** file descriptor might have already been reused by another thread.
1150** So we don't even try to recover from an EINTR. Just log the error
1151** and move on.
1152*/
1153static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001154 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001155 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1156 pFile ? pFile->zPath : 0, lineno);
1157 }
1158}
dane18d4952011-02-21 11:46:24 +00001159
1160/*
danb0ac3e32010-06-16 10:55:42 +00001161** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001162*/
drh0e9365c2011-03-02 02:08:13 +00001163static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001164 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001165 UnixUnusedFd *p;
1166 UnixUnusedFd *pNext;
1167 for(p=pInode->pUnused; p; p=pNext){
1168 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001169 robust_close(pFile, p->fd, __LINE__);
1170 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001171 }
drh0e9365c2011-03-02 02:08:13 +00001172 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001173}
1174
1175/*
drh8af6c222010-05-14 12:43:01 +00001176** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001177**
1178** The mutex entered using the unixEnterMutex() function must be held
1179** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001180*/
danb0ac3e32010-06-16 10:55:42 +00001181static void releaseInodeInfo(unixFile *pFile){
1182 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001183 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001184 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001185 pInode->nRef--;
1186 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001187 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001188 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001189 if( pInode->pPrev ){
1190 assert( pInode->pPrev->pNext==pInode );
1191 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001192 }else{
drh8af6c222010-05-14 12:43:01 +00001193 assert( inodeList==pInode );
1194 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001195 }
drh8af6c222010-05-14 12:43:01 +00001196 if( pInode->pNext ){
1197 assert( pInode->pNext->pPrev==pInode );
1198 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001199 }
drh8af6c222010-05-14 12:43:01 +00001200 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001201 }
drhbbd42a62004-05-22 17:41:58 +00001202 }
1203}
1204
1205/*
drh8af6c222010-05-14 12:43:01 +00001206** Given a file descriptor, locate the unixInodeInfo object that
1207** describes that file descriptor. Create a new one if necessary. The
1208** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001209**
dan9359c7b2009-08-21 08:29:10 +00001210** The mutex entered using the unixEnterMutex() function must be held
1211** when this function is called.
1212**
drh6c7d5c52008-11-21 20:32:33 +00001213** Return an appropriate error code.
1214*/
drh8af6c222010-05-14 12:43:01 +00001215static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001216 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001217 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001218){
1219 int rc; /* System call return code */
1220 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001221 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1222 struct stat statbuf; /* Low-level file information */
1223 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001224
dan9359c7b2009-08-21 08:29:10 +00001225 assert( unixMutexHeld() );
1226
drh6c7d5c52008-11-21 20:32:33 +00001227 /* Get low-level information about the file that we can used to
1228 ** create a unique name for the file.
1229 */
1230 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001231 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001232 if( rc!=0 ){
1233 pFile->lastErrno = errno;
1234#ifdef EOVERFLOW
1235 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1236#endif
1237 return SQLITE_IOERR;
1238 }
1239
drheb0d74f2009-02-03 15:27:02 +00001240#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001241 /* On OS X on an msdos filesystem, the inode number is reported
1242 ** incorrectly for zero-size files. See ticket #3260. To work
1243 ** around this problem (we consider it a bug in OS X, not SQLite)
1244 ** we always increase the file size to 1 by writing a single byte
1245 ** prior to accessing the inode number. The one byte written is
1246 ** an ASCII 'S' character which also happens to be the first byte
1247 ** in the header of every SQLite database. In this way, if there
1248 ** is a race condition such that another thread has already populated
1249 ** the first page of the database, no damage is done.
1250 */
drh7ed97b92010-01-20 13:07:21 +00001251 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001252 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001253 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001254 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001255 return SQLITE_IOERR;
1256 }
drh99ab3b12011-03-02 15:09:07 +00001257 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001258 if( rc!=0 ){
1259 pFile->lastErrno = errno;
1260 return SQLITE_IOERR;
1261 }
1262 }
drheb0d74f2009-02-03 15:27:02 +00001263#endif
drh6c7d5c52008-11-21 20:32:33 +00001264
drh8af6c222010-05-14 12:43:01 +00001265 memset(&fileId, 0, sizeof(fileId));
1266 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001267#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001268 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001269#else
drh8af6c222010-05-14 12:43:01 +00001270 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001271#endif
drh8af6c222010-05-14 12:43:01 +00001272 pInode = inodeList;
1273 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1274 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001275 }
drh8af6c222010-05-14 12:43:01 +00001276 if( pInode==0 ){
1277 pInode = sqlite3_malloc( sizeof(*pInode) );
1278 if( pInode==0 ){
1279 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001280 }
drh8af6c222010-05-14 12:43:01 +00001281 memset(pInode, 0, sizeof(*pInode));
1282 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1283 pInode->nRef = 1;
1284 pInode->pNext = inodeList;
1285 pInode->pPrev = 0;
1286 if( inodeList ) inodeList->pPrev = pInode;
1287 inodeList = pInode;
1288 }else{
1289 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001290 }
drh8af6c222010-05-14 12:43:01 +00001291 *ppInode = pInode;
1292 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001293}
drh6c7d5c52008-11-21 20:32:33 +00001294
aswift5b1a2562008-08-22 00:22:35 +00001295
1296/*
drhfbc7e882013-04-11 01:16:15 +00001297** Check a unixFile that is a database. Verify the following:
1298**
1299** (1) There is exactly one hard link on the file
1300** (2) The file is not a symbolic link
1301** (3) The file has not been renamed or unlinked
1302**
1303** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1304*/
1305static void verifyDbFile(unixFile *pFile){
1306 struct stat buf;
1307 int rc;
1308 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1309 /* One or more of the following warnings have already been issued. Do not
1310 ** repeat them so as not to clutter the error log */
1311 return;
1312 }
1313 rc = osFstat(pFile->h, &buf);
1314 if( rc!=0 ){
1315 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1316 pFile->ctrlFlags |= UNIXFILE_WARNED;
1317 return;
1318 }
1319 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
1320 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1321 pFile->ctrlFlags |= UNIXFILE_WARNED;
1322 return;
1323 }
1324 if( buf.st_nlink>1 ){
1325 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1326 pFile->ctrlFlags |= UNIXFILE_WARNED;
1327 return;
1328 }
1329 if( pFile->pInode!=0
1330 && ((rc = osStat(pFile->zPath, &buf))!=0
1331 || buf.st_ino!=pFile->pInode->fileId.ino)
1332 ){
1333 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1334 pFile->ctrlFlags |= UNIXFILE_WARNED;
1335 return;
1336 }
1337}
1338
1339
1340/*
danielk197713adf8a2004-06-03 16:08:41 +00001341** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001342** file by this or any other process. If such a lock is held, set *pResOut
1343** to a non-zero value otherwise *pResOut is set to zero. The return value
1344** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001345*/
danielk1977861f7452008-06-05 11:39:11 +00001346static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001347 int rc = SQLITE_OK;
1348 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001349 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001350
danielk1977861f7452008-06-05 11:39:11 +00001351 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1352
drh054889e2005-11-30 03:20:31 +00001353 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001354 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001355
1356 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001357 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001358 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001359 }
1360
drh2ac3ee92004-06-07 16:27:46 +00001361 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001362 */
danielk197709480a92009-02-09 05:32:32 +00001363#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001364 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001365 struct flock lock;
1366 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001367 lock.l_start = RESERVED_BYTE;
1368 lock.l_len = 1;
1369 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001370 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1371 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1372 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001373 } else if( lock.l_type!=F_UNLCK ){
1374 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001375 }
1376 }
danielk197709480a92009-02-09 05:32:32 +00001377#endif
danielk197713adf8a2004-06-03 16:08:41 +00001378
drh6c7d5c52008-11-21 20:32:33 +00001379 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001380 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001381
aswift5b1a2562008-08-22 00:22:35 +00001382 *pResOut = reserved;
1383 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001384}
1385
1386/*
drha7e61d82011-03-12 17:02:57 +00001387** Attempt to set a system-lock on the file pFile. The lock is
1388** described by pLock.
1389**
drh77197112011-03-15 19:08:48 +00001390** If the pFile was opened read/write from unix-excl, then the only lock
1391** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001392** the first time any lock is attempted. All subsequent system locking
1393** operations become no-ops. Locking operations still happen internally,
1394** in order to coordinate access between separate database connections
1395** within this process, but all of that is handled in memory and the
1396** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001397**
1398** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1399** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1400** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001401**
1402** Zero is returned if the call completes successfully, or -1 if a call
1403** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001404*/
1405static int unixFileLock(unixFile *pFile, struct flock *pLock){
1406 int rc;
drh3cb93392011-03-12 18:10:44 +00001407 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001408 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001409 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001410 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1411 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1412 ){
drh3cb93392011-03-12 18:10:44 +00001413 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001414 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001415 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001416 lock.l_whence = SEEK_SET;
1417 lock.l_start = SHARED_FIRST;
1418 lock.l_len = SHARED_SIZE;
1419 lock.l_type = F_WRLCK;
1420 rc = osFcntl(pFile->h, F_SETLK, &lock);
1421 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001422 pInode->bProcessLock = 1;
1423 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001424 }else{
1425 rc = 0;
1426 }
1427 }else{
1428 rc = osFcntl(pFile->h, F_SETLK, pLock);
1429 }
1430 return rc;
1431}
1432
1433/*
drh308c2a52010-05-14 11:30:18 +00001434** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001435** of the following:
1436**
drh2ac3ee92004-06-07 16:27:46 +00001437** (1) SHARED_LOCK
1438** (2) RESERVED_LOCK
1439** (3) PENDING_LOCK
1440** (4) EXCLUSIVE_LOCK
1441**
drhb3e04342004-06-08 00:47:47 +00001442** Sometimes when requesting one lock state, additional lock states
1443** are inserted in between. The locking might fail on one of the later
1444** transitions leaving the lock state different from what it started but
1445** still short of its goal. The following chart shows the allowed
1446** transitions and the inserted intermediate states:
1447**
1448** UNLOCKED -> SHARED
1449** SHARED -> RESERVED
1450** SHARED -> (PENDING) -> EXCLUSIVE
1451** RESERVED -> (PENDING) -> EXCLUSIVE
1452** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001453**
drha6abd042004-06-09 17:37:22 +00001454** This routine will only increase a lock. Use the sqlite3OsUnlock()
1455** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001456*/
drh308c2a52010-05-14 11:30:18 +00001457static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001458 /* The following describes the implementation of the various locks and
1459 ** lock transitions in terms of the POSIX advisory shared and exclusive
1460 ** lock primitives (called read-locks and write-locks below, to avoid
1461 ** confusion with SQLite lock names). The algorithms are complicated
1462 ** slightly in order to be compatible with windows systems simultaneously
1463 ** accessing the same database file, in case that is ever required.
1464 **
1465 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1466 ** byte', each single bytes at well known offsets, and the 'shared byte
1467 ** range', a range of 510 bytes at a well known offset.
1468 **
1469 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1470 ** byte'. If this is successful, a random byte from the 'shared byte
1471 ** range' is read-locked and the lock on the 'pending byte' released.
1472 **
danielk197790ba3bd2004-06-25 08:32:25 +00001473 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1474 ** A RESERVED lock is implemented by grabbing a write-lock on the
1475 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001476 **
1477 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001478 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1479 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1480 ** obtained, but existing SHARED locks are allowed to persist. A process
1481 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1482 ** This property is used by the algorithm for rolling back a journal file
1483 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001484 **
danielk197790ba3bd2004-06-25 08:32:25 +00001485 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1486 ** implemented by obtaining a write-lock on the entire 'shared byte
1487 ** range'. Since all other locks require a read-lock on one of the bytes
1488 ** within this range, this ensures that no other locks are held on the
1489 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001490 **
1491 ** The reason a single byte cannot be used instead of the 'shared byte
1492 ** range' is that some versions of windows do not support read-locks. By
1493 ** locking a random byte from a range, concurrent SHARED locks may exist
1494 ** even if the locking primitive used is always a write-lock.
1495 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001496 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001497 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001498 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001499 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001500 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001501
drh054889e2005-11-30 03:20:31 +00001502 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001503 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1504 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001505 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001506
1507 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001508 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001509 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001510 */
drh308c2a52010-05-14 11:30:18 +00001511 if( pFile->eFileLock>=eFileLock ){
1512 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1513 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001514 return SQLITE_OK;
1515 }
1516
drh0c2694b2009-09-03 16:23:44 +00001517 /* Make sure the locking sequence is correct.
1518 ** (1) We never move from unlocked to anything higher than shared lock.
1519 ** (2) SQLite never explicitly requests a pendig lock.
1520 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001521 */
drh308c2a52010-05-14 11:30:18 +00001522 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1523 assert( eFileLock!=PENDING_LOCK );
1524 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001525
drh8af6c222010-05-14 12:43:01 +00001526 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001527 */
drh6c7d5c52008-11-21 20:32:33 +00001528 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001529 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001530
danielk1977ad94b582007-08-20 06:44:22 +00001531 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001532 ** handle that precludes the requested lock, return BUSY.
1533 */
drh8af6c222010-05-14 12:43:01 +00001534 if( (pFile->eFileLock!=pInode->eFileLock &&
1535 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001536 ){
1537 rc = SQLITE_BUSY;
1538 goto end_lock;
1539 }
1540
1541 /* If a SHARED lock is requested, and some thread using this PID already
1542 ** has a SHARED or RESERVED lock, then increment reference counts and
1543 ** return SQLITE_OK.
1544 */
drh308c2a52010-05-14 11:30:18 +00001545 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001546 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001547 assert( eFileLock==SHARED_LOCK );
1548 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001549 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001550 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001551 pInode->nShared++;
1552 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001553 goto end_lock;
1554 }
1555
danielk19779a1d0ab2004-06-01 14:09:28 +00001556
drh3cde3bb2004-06-12 02:17:14 +00001557 /* A PENDING lock is needed before acquiring a SHARED lock and before
1558 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1559 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001560 */
drh0c2694b2009-09-03 16:23:44 +00001561 lock.l_len = 1L;
1562 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001563 if( eFileLock==SHARED_LOCK
1564 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001565 ){
drh308c2a52010-05-14 11:30:18 +00001566 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001567 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001568 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001569 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001570 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001571 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001572 pFile->lastErrno = tErrno;
1573 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001574 goto end_lock;
1575 }
drh3cde3bb2004-06-12 02:17:14 +00001576 }
1577
1578
1579 /* If control gets to this point, then actually go ahead and make
1580 ** operating system calls for the specified lock.
1581 */
drh308c2a52010-05-14 11:30:18 +00001582 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001583 assert( pInode->nShared==0 );
1584 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001585 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001586
drh2ac3ee92004-06-07 16:27:46 +00001587 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001588 lock.l_start = SHARED_FIRST;
1589 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001590 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001591 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001592 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001593 }
dan661d71a2011-03-30 19:08:03 +00001594
drh2ac3ee92004-06-07 16:27:46 +00001595 /* Drop the temporary PENDING lock */
1596 lock.l_start = PENDING_BYTE;
1597 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001598 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001599 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1600 /* This could happen with a network mount */
1601 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001602 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001603 }
dan661d71a2011-03-30 19:08:03 +00001604
1605 if( rc ){
1606 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001607 pFile->lastErrno = tErrno;
1608 }
dan661d71a2011-03-30 19:08:03 +00001609 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001610 }else{
drh308c2a52010-05-14 11:30:18 +00001611 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001612 pInode->nLock++;
1613 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001614 }
drh8af6c222010-05-14 12:43:01 +00001615 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001616 /* We are trying for an exclusive lock but another thread in this
1617 ** same process is still holding a shared lock. */
1618 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001619 }else{
drh3cde3bb2004-06-12 02:17:14 +00001620 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001621 ** assumed that there is a SHARED or greater lock on the file
1622 ** already.
1623 */
drh308c2a52010-05-14 11:30:18 +00001624 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001625 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001626
1627 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1628 if( eFileLock==RESERVED_LOCK ){
1629 lock.l_start = RESERVED_BYTE;
1630 lock.l_len = 1L;
1631 }else{
1632 lock.l_start = SHARED_FIRST;
1633 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001634 }
dan661d71a2011-03-30 19:08:03 +00001635
1636 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001637 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001638 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001639 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001640 pFile->lastErrno = tErrno;
1641 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001642 }
drhbbd42a62004-05-22 17:41:58 +00001643 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001644
drh8f941bc2009-01-14 23:03:40 +00001645
drhd3d8c042012-05-29 17:02:40 +00001646#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001647 /* Set up the transaction-counter change checking flags when
1648 ** transitioning from a SHARED to a RESERVED lock. The change
1649 ** from SHARED to RESERVED marks the beginning of a normal
1650 ** write operation (not a hot journal rollback).
1651 */
1652 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001653 && pFile->eFileLock<=SHARED_LOCK
1654 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001655 ){
1656 pFile->transCntrChng = 0;
1657 pFile->dbUpdate = 0;
1658 pFile->inNormalWrite = 1;
1659 }
1660#endif
1661
1662
danielk1977ecb2a962004-06-02 06:30:16 +00001663 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001664 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001665 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001666 }else if( eFileLock==EXCLUSIVE_LOCK ){
1667 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001668 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001669 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001670
1671end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001672 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001673 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1674 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001675 return rc;
1676}
1677
1678/*
dan08da86a2009-08-21 17:18:03 +00001679** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001680** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001681*/
1682static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001683 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001684 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001685 p->pNext = pInode->pUnused;
1686 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001687 pFile->h = -1;
1688 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001689}
1690
1691/*
drh308c2a52010-05-14 11:30:18 +00001692** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001693** must be either NO_LOCK or SHARED_LOCK.
1694**
1695** If the locking level of the file descriptor is already at or below
1696** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001697**
1698** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1699** the byte range is divided into 2 parts and the first part is unlocked then
1700** set to a read lock, then the other part is simply unlocked. This works
1701** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1702** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001703*/
drha7e61d82011-03-12 17:02:57 +00001704static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001705 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001706 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001707 struct flock lock;
1708 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001709
drh054889e2005-11-30 03:20:31 +00001710 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001711 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001712 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001713 getpid()));
drha6abd042004-06-09 17:37:22 +00001714
drh308c2a52010-05-14 11:30:18 +00001715 assert( eFileLock<=SHARED_LOCK );
1716 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001717 return SQLITE_OK;
1718 }
drh6c7d5c52008-11-21 20:32:33 +00001719 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001720 pInode = pFile->pInode;
1721 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001722 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001723 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001724
drhd3d8c042012-05-29 17:02:40 +00001725#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001726 /* When reducing a lock such that other processes can start
1727 ** reading the database file again, make sure that the
1728 ** transaction counter was updated if any part of the database
1729 ** file changed. If the transaction counter is not updated,
1730 ** other connections to the same file might not realize that
1731 ** the file has changed and hence might not know to flush their
1732 ** cache. The use of a stale cache can lead to database corruption.
1733 */
drh8f941bc2009-01-14 23:03:40 +00001734 pFile->inNormalWrite = 0;
1735#endif
1736
drh7ed97b92010-01-20 13:07:21 +00001737 /* downgrading to a shared lock on NFS involves clearing the write lock
1738 ** before establishing the readlock - to avoid a race condition we downgrade
1739 ** the lock in 2 blocks, so that part of the range will be covered by a
1740 ** write lock until the rest is covered by a read lock:
1741 ** 1: [WWWWW]
1742 ** 2: [....W]
1743 ** 3: [RRRRW]
1744 ** 4: [RRRR.]
1745 */
drh308c2a52010-05-14 11:30:18 +00001746 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001747
1748#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001749 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001750 assert( handleNFSUnlock==0 );
1751#endif
1752#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001753 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001754 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001755 off_t divSize = SHARED_SIZE - 1;
1756
1757 lock.l_type = F_UNLCK;
1758 lock.l_whence = SEEK_SET;
1759 lock.l_start = SHARED_FIRST;
1760 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001761 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001762 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001763 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001764 if( IS_LOCK_ERROR(rc) ){
1765 pFile->lastErrno = tErrno;
1766 }
1767 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001768 }
drh7ed97b92010-01-20 13:07:21 +00001769 lock.l_type = F_RDLCK;
1770 lock.l_whence = SEEK_SET;
1771 lock.l_start = SHARED_FIRST;
1772 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001773 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001774 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001775 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1776 if( IS_LOCK_ERROR(rc) ){
1777 pFile->lastErrno = tErrno;
1778 }
1779 goto end_unlock;
1780 }
1781 lock.l_type = F_UNLCK;
1782 lock.l_whence = SEEK_SET;
1783 lock.l_start = SHARED_FIRST+divSize;
1784 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001785 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001786 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001787 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001788 if( IS_LOCK_ERROR(rc) ){
1789 pFile->lastErrno = tErrno;
1790 }
1791 goto end_unlock;
1792 }
drh30f776f2011-02-25 03:25:07 +00001793 }else
1794#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1795 {
drh7ed97b92010-01-20 13:07:21 +00001796 lock.l_type = F_RDLCK;
1797 lock.l_whence = SEEK_SET;
1798 lock.l_start = SHARED_FIRST;
1799 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001800 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001801 /* In theory, the call to unixFileLock() cannot fail because another
1802 ** process is holding an incompatible lock. If it does, this
1803 ** indicates that the other process is not following the locking
1804 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1805 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1806 ** an assert to fail). */
1807 rc = SQLITE_IOERR_RDLOCK;
1808 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001809 goto end_unlock;
1810 }
drh9c105bb2004-10-02 20:38:28 +00001811 }
1812 }
drhbbd42a62004-05-22 17:41:58 +00001813 lock.l_type = F_UNLCK;
1814 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001815 lock.l_start = PENDING_BYTE;
1816 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001817 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001818 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001819 }else{
danea83bc62011-04-01 11:56:32 +00001820 rc = SQLITE_IOERR_UNLOCK;
1821 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001822 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001823 }
drhbbd42a62004-05-22 17:41:58 +00001824 }
drh308c2a52010-05-14 11:30:18 +00001825 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001826 /* Decrement the shared lock counter. Release the lock using an
1827 ** OS call only when all threads in this same process have released
1828 ** the lock.
1829 */
drh8af6c222010-05-14 12:43:01 +00001830 pInode->nShared--;
1831 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001832 lock.l_type = F_UNLCK;
1833 lock.l_whence = SEEK_SET;
1834 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001835 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001836 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001837 }else{
danea83bc62011-04-01 11:56:32 +00001838 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001839 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001840 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001841 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001842 }
drha6abd042004-06-09 17:37:22 +00001843 }
1844
drhbbd42a62004-05-22 17:41:58 +00001845 /* Decrement the count of locks against this same file. When the
1846 ** count reaches zero, close any other file descriptors whose close
1847 ** was deferred because of outstanding locks.
1848 */
drh8af6c222010-05-14 12:43:01 +00001849 pInode->nLock--;
1850 assert( pInode->nLock>=0 );
1851 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001852 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001853 }
1854 }
drhf2f105d2012-08-20 15:53:54 +00001855
aswift5b1a2562008-08-22 00:22:35 +00001856end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001857 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001858 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001859 return rc;
drhbbd42a62004-05-22 17:41:58 +00001860}
1861
1862/*
drh308c2a52010-05-14 11:30:18 +00001863** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001864** must be either NO_LOCK or SHARED_LOCK.
1865**
1866** If the locking level of the file descriptor is already at or below
1867** the requested locking level, this routine is a no-op.
1868*/
drh308c2a52010-05-14 11:30:18 +00001869static int unixUnlock(sqlite3_file *id, int eFileLock){
dana1afc742013-03-25 13:50:49 +00001870 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
drha7e61d82011-03-12 17:02:57 +00001871 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001872}
1873
danf23da962013-03-23 21:00:41 +00001874static int unixMapfile(unixFile *pFd, i64 nByte);
1875static void unixUnmapfile(unixFile *pFd);
1876
drh7ed97b92010-01-20 13:07:21 +00001877/*
danielk1977e339d652008-06-28 11:23:00 +00001878** This function performs the parts of the "close file" operation
1879** common to all locking schemes. It closes the directory and file
1880** handles, if they are valid, and sets all fields of the unixFile
1881** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001882**
1883** It is *not* necessary to hold the mutex when this routine is called,
1884** even on VxWorks. A mutex will be acquired on VxWorks by the
1885** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001886*/
1887static int closeUnixFile(sqlite3_file *id){
1888 unixFile *pFile = (unixFile*)id;
danf23da962013-03-23 21:00:41 +00001889 unixUnmapfile(pFile);
dan661d71a2011-03-30 19:08:03 +00001890 if( pFile->h>=0 ){
1891 robust_close(pFile, pFile->h, __LINE__);
1892 pFile->h = -1;
1893 }
1894#if OS_VXWORKS
1895 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001896 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001897 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001898 }
1899 vxworksReleaseFileId(pFile->pId);
1900 pFile->pId = 0;
1901 }
1902#endif
1903 OSTRACE(("CLOSE %-3d\n", pFile->h));
1904 OpenCounter(-1);
1905 sqlite3_free(pFile->pUnused);
1906 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001907 return SQLITE_OK;
1908}
1909
1910/*
danielk1977e3026632004-06-22 11:29:02 +00001911** Close a file.
1912*/
danielk197762079062007-08-15 17:08:46 +00001913static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001914 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001915 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001916 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001917 unixUnlock(id, NO_LOCK);
1918 unixEnterMutex();
1919
1920 /* unixFile.pInode is always valid here. Otherwise, a different close
1921 ** routine (e.g. nolockClose()) would be called instead.
1922 */
1923 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1924 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1925 /* If there are outstanding locks, do not actually close the file just
1926 ** yet because that would clear those locks. Instead, add the file
1927 ** descriptor to pInode->pUnused list. It will be automatically closed
1928 ** when the last lock is cleared.
1929 */
1930 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001931 }
dan661d71a2011-03-30 19:08:03 +00001932 releaseInodeInfo(pFile);
1933 rc = closeUnixFile(id);
1934 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001935 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001936}
1937
drh734c9862008-11-28 15:37:20 +00001938/************** End of the posix advisory lock implementation *****************
1939******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001940
drh734c9862008-11-28 15:37:20 +00001941/******************************************************************************
1942****************************** No-op Locking **********************************
1943**
1944** Of the various locking implementations available, this is by far the
1945** simplest: locking is ignored. No attempt is made to lock the database
1946** file for reading or writing.
1947**
1948** This locking mode is appropriate for use on read-only databases
1949** (ex: databases that are burned into CD-ROM, for example.) It can
1950** also be used if the application employs some external mechanism to
1951** prevent simultaneous access of the same database by two or more
1952** database connections. But there is a serious risk of database
1953** corruption if this locking mode is used in situations where multiple
1954** database connections are accessing the same database file at the same
1955** time and one or more of those connections are writing.
1956*/
drhbfe66312006-10-03 17:40:40 +00001957
drh734c9862008-11-28 15:37:20 +00001958static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1959 UNUSED_PARAMETER(NotUsed);
1960 *pResOut = 0;
1961 return SQLITE_OK;
1962}
drh734c9862008-11-28 15:37:20 +00001963static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1964 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1965 return SQLITE_OK;
1966}
drh734c9862008-11-28 15:37:20 +00001967static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1968 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1969 return SQLITE_OK;
1970}
1971
1972/*
drh9b35ea62008-11-29 02:20:26 +00001973** Close the file.
drh734c9862008-11-28 15:37:20 +00001974*/
1975static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001976 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001977}
1978
1979/******************* End of the no-op lock implementation *********************
1980******************************************************************************/
1981
1982/******************************************************************************
1983************************* Begin dot-file Locking ******************************
1984**
mistachkin48864df2013-03-21 21:20:32 +00001985** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001986** files (really a directory) to control access to the database. This works
1987** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001988**
1989** (1) There is zero concurrency. A single reader blocks all other
1990** connections from reading or writing the database.
1991**
1992** (2) An application crash or power loss can leave stale lock files
1993** sitting around that need to be cleared manually.
1994**
1995** Nevertheless, a dotlock is an appropriate locking mode for use if no
1996** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001997**
drh9ef6bc42011-11-04 02:24:02 +00001998** Dotfile locking works by creating a subdirectory in the same directory as
1999** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002000** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002001** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002002*/
2003
2004/*
2005** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002006** lock directory.
drh734c9862008-11-28 15:37:20 +00002007*/
2008#define DOTLOCK_SUFFIX ".lock"
2009
drh7708e972008-11-29 00:56:52 +00002010/*
2011** This routine checks if there is a RESERVED lock held on the specified
2012** file by this or any other process. If such a lock is held, set *pResOut
2013** to a non-zero value otherwise *pResOut is set to zero. The return value
2014** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2015**
2016** In dotfile locking, either a lock exists or it does not. So in this
2017** variation of CheckReservedLock(), *pResOut is set to true if any lock
2018** is held on the file and false if the file is unlocked.
2019*/
drh734c9862008-11-28 15:37:20 +00002020static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2021 int rc = SQLITE_OK;
2022 int reserved = 0;
2023 unixFile *pFile = (unixFile*)id;
2024
2025 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2026
2027 assert( pFile );
2028
2029 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002030 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002031 /* Either this connection or some other connection in the same process
2032 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002033 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002034 }else{
2035 /* The lock is held if and only if the lockfile exists */
2036 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002037 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002038 }
drh308c2a52010-05-14 11:30:18 +00002039 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002040 *pResOut = reserved;
2041 return rc;
2042}
2043
drh7708e972008-11-29 00:56:52 +00002044/*
drh308c2a52010-05-14 11:30:18 +00002045** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002046** of the following:
2047**
2048** (1) SHARED_LOCK
2049** (2) RESERVED_LOCK
2050** (3) PENDING_LOCK
2051** (4) EXCLUSIVE_LOCK
2052**
2053** Sometimes when requesting one lock state, additional lock states
2054** are inserted in between. The locking might fail on one of the later
2055** transitions leaving the lock state different from what it started but
2056** still short of its goal. The following chart shows the allowed
2057** transitions and the inserted intermediate states:
2058**
2059** UNLOCKED -> SHARED
2060** SHARED -> RESERVED
2061** SHARED -> (PENDING) -> EXCLUSIVE
2062** RESERVED -> (PENDING) -> EXCLUSIVE
2063** PENDING -> EXCLUSIVE
2064**
2065** This routine will only increase a lock. Use the sqlite3OsUnlock()
2066** routine to lower a locking level.
2067**
2068** With dotfile locking, we really only support state (4): EXCLUSIVE.
2069** But we track the other locking levels internally.
2070*/
drh308c2a52010-05-14 11:30:18 +00002071static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002072 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002073 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002074 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002075
drh7708e972008-11-29 00:56:52 +00002076
2077 /* If we have any lock, then the lock file already exists. All we have
2078 ** to do is adjust our internal record of the lock level.
2079 */
drh308c2a52010-05-14 11:30:18 +00002080 if( pFile->eFileLock > NO_LOCK ){
2081 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002082 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002083#ifdef HAVE_UTIME
2084 utime(zLockFile, NULL);
2085#else
drh734c9862008-11-28 15:37:20 +00002086 utimes(zLockFile, NULL);
2087#endif
drh7708e972008-11-29 00:56:52 +00002088 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002089 }
2090
2091 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002092 rc = osMkdir(zLockFile, 0777);
2093 if( rc<0 ){
2094 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002095 int tErrno = errno;
2096 if( EEXIST == tErrno ){
2097 rc = SQLITE_BUSY;
2098 } else {
2099 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2100 if( IS_LOCK_ERROR(rc) ){
2101 pFile->lastErrno = tErrno;
2102 }
2103 }
drh7708e972008-11-29 00:56:52 +00002104 return rc;
drh734c9862008-11-28 15:37:20 +00002105 }
drh734c9862008-11-28 15:37:20 +00002106
2107 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002108 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002109 return rc;
2110}
2111
drh7708e972008-11-29 00:56:52 +00002112/*
drh308c2a52010-05-14 11:30:18 +00002113** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002114** must be either NO_LOCK or SHARED_LOCK.
2115**
2116** If the locking level of the file descriptor is already at or below
2117** the requested locking level, this routine is a no-op.
2118**
2119** When the locking level reaches NO_LOCK, delete the lock file.
2120*/
drh308c2a52010-05-14 11:30:18 +00002121static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002122 unixFile *pFile = (unixFile*)id;
2123 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002124 int rc;
drh734c9862008-11-28 15:37:20 +00002125
2126 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002127 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002128 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002129 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002130
2131 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002132 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002133 return SQLITE_OK;
2134 }
drh7708e972008-11-29 00:56:52 +00002135
2136 /* To downgrade to shared, simply update our internal notion of the
2137 ** lock state. No need to mess with the file on disk.
2138 */
drh308c2a52010-05-14 11:30:18 +00002139 if( eFileLock==SHARED_LOCK ){
2140 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002141 return SQLITE_OK;
2142 }
2143
drh7708e972008-11-29 00:56:52 +00002144 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002145 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002146 rc = osRmdir(zLockFile);
2147 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2148 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002149 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002150 rc = 0;
drh734c9862008-11-28 15:37:20 +00002151 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002152 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002153 }
2154 if( IS_LOCK_ERROR(rc) ){
2155 pFile->lastErrno = tErrno;
2156 }
2157 return rc;
2158 }
drh308c2a52010-05-14 11:30:18 +00002159 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002160 return SQLITE_OK;
2161}
2162
2163/*
drh9b35ea62008-11-29 02:20:26 +00002164** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002165*/
2166static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002167 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002168 if( id ){
2169 unixFile *pFile = (unixFile*)id;
2170 dotlockUnlock(id, NO_LOCK);
2171 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002172 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002173 }
drh734c9862008-11-28 15:37:20 +00002174 return rc;
2175}
2176/****************** End of the dot-file lock implementation *******************
2177******************************************************************************/
2178
2179/******************************************************************************
2180************************** Begin flock Locking ********************************
2181**
2182** Use the flock() system call to do file locking.
2183**
drh6b9d6dd2008-12-03 19:34:47 +00002184** flock() locking is like dot-file locking in that the various
2185** fine-grain locking levels supported by SQLite are collapsed into
2186** a single exclusive lock. In other words, SHARED, RESERVED, and
2187** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2188** still works when you do this, but concurrency is reduced since
2189** only a single process can be reading the database at a time.
2190**
drh734c9862008-11-28 15:37:20 +00002191** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2192** compiling for VXWORKS.
2193*/
2194#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002195
drh6b9d6dd2008-12-03 19:34:47 +00002196/*
drhff812312011-02-23 13:33:46 +00002197** Retry flock() calls that fail with EINTR
2198*/
2199#ifdef EINTR
2200static int robust_flock(int fd, int op){
2201 int rc;
2202 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2203 return rc;
2204}
2205#else
drh5c819272011-02-23 14:00:12 +00002206# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002207#endif
2208
2209
2210/*
drh6b9d6dd2008-12-03 19:34:47 +00002211** This routine checks if there is a RESERVED lock held on the specified
2212** file by this or any other process. If such a lock is held, set *pResOut
2213** to a non-zero value otherwise *pResOut is set to zero. The return value
2214** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2215*/
drh734c9862008-11-28 15:37:20 +00002216static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2217 int rc = SQLITE_OK;
2218 int reserved = 0;
2219 unixFile *pFile = (unixFile*)id;
2220
2221 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2222
2223 assert( pFile );
2224
2225 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002226 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002227 reserved = 1;
2228 }
2229
2230 /* Otherwise see if some other process holds it. */
2231 if( !reserved ){
2232 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002233 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002234 if( !lrc ){
2235 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002236 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002237 if ( lrc ) {
2238 int tErrno = errno;
2239 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002240 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002241 if( IS_LOCK_ERROR(lrc) ){
2242 pFile->lastErrno = tErrno;
2243 rc = lrc;
2244 }
2245 }
2246 } else {
2247 int tErrno = errno;
2248 reserved = 1;
2249 /* someone else might have it reserved */
2250 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2251 if( IS_LOCK_ERROR(lrc) ){
2252 pFile->lastErrno = tErrno;
2253 rc = lrc;
2254 }
2255 }
2256 }
drh308c2a52010-05-14 11:30:18 +00002257 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002258
2259#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2260 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2261 rc = SQLITE_OK;
2262 reserved=1;
2263 }
2264#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2265 *pResOut = reserved;
2266 return rc;
2267}
2268
drh6b9d6dd2008-12-03 19:34:47 +00002269/*
drh308c2a52010-05-14 11:30:18 +00002270** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002271** of the following:
2272**
2273** (1) SHARED_LOCK
2274** (2) RESERVED_LOCK
2275** (3) PENDING_LOCK
2276** (4) EXCLUSIVE_LOCK
2277**
2278** Sometimes when requesting one lock state, additional lock states
2279** are inserted in between. The locking might fail on one of the later
2280** transitions leaving the lock state different from what it started but
2281** still short of its goal. The following chart shows the allowed
2282** transitions and the inserted intermediate states:
2283**
2284** UNLOCKED -> SHARED
2285** SHARED -> RESERVED
2286** SHARED -> (PENDING) -> EXCLUSIVE
2287** RESERVED -> (PENDING) -> EXCLUSIVE
2288** PENDING -> EXCLUSIVE
2289**
2290** flock() only really support EXCLUSIVE locks. We track intermediate
2291** lock states in the sqlite3_file structure, but all locks SHARED or
2292** above are really EXCLUSIVE locks and exclude all other processes from
2293** access the file.
2294**
2295** This routine will only increase a lock. Use the sqlite3OsUnlock()
2296** routine to lower a locking level.
2297*/
drh308c2a52010-05-14 11:30:18 +00002298static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002299 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002300 unixFile *pFile = (unixFile*)id;
2301
2302 assert( pFile );
2303
2304 /* if we already have a lock, it is exclusive.
2305 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002306 if (pFile->eFileLock > NO_LOCK) {
2307 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002308 return SQLITE_OK;
2309 }
2310
2311 /* grab an exclusive lock */
2312
drhff812312011-02-23 13:33:46 +00002313 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002314 int tErrno = errno;
2315 /* didn't get, must be busy */
2316 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2317 if( IS_LOCK_ERROR(rc) ){
2318 pFile->lastErrno = tErrno;
2319 }
2320 } else {
2321 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002322 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002323 }
drh308c2a52010-05-14 11:30:18 +00002324 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2325 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002326#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2327 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2328 rc = SQLITE_BUSY;
2329 }
2330#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2331 return rc;
2332}
2333
drh6b9d6dd2008-12-03 19:34:47 +00002334
2335/*
drh308c2a52010-05-14 11:30:18 +00002336** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002337** must be either NO_LOCK or SHARED_LOCK.
2338**
2339** If the locking level of the file descriptor is already at or below
2340** the requested locking level, this routine is a no-op.
2341*/
drh308c2a52010-05-14 11:30:18 +00002342static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002343 unixFile *pFile = (unixFile*)id;
2344
2345 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002346 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2347 pFile->eFileLock, getpid()));
2348 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002349
2350 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002351 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002352 return SQLITE_OK;
2353 }
2354
2355 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002356 if (eFileLock==SHARED_LOCK) {
2357 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002358 return SQLITE_OK;
2359 }
2360
2361 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002362 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002363#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002364 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002365#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002366 return SQLITE_IOERR_UNLOCK;
2367 }else{
drh308c2a52010-05-14 11:30:18 +00002368 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002369 return SQLITE_OK;
2370 }
2371}
2372
2373/*
2374** Close a file.
2375*/
2376static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002377 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002378 if( id ){
2379 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002380 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002381 }
drh5a05be12012-10-09 18:51:44 +00002382 return rc;
drh734c9862008-11-28 15:37:20 +00002383}
2384
2385#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2386
2387/******************* End of the flock lock implementation *********************
2388******************************************************************************/
2389
2390/******************************************************************************
2391************************ Begin Named Semaphore Locking ************************
2392**
2393** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002394**
2395** Semaphore locking is like dot-lock and flock in that it really only
2396** supports EXCLUSIVE locking. Only a single process can read or write
2397** the database file at a time. This reduces potential concurrency, but
2398** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002399*/
2400#if OS_VXWORKS
2401
drh6b9d6dd2008-12-03 19:34:47 +00002402/*
2403** This routine checks if there is a RESERVED lock held on the specified
2404** file by this or any other process. If such a lock is held, set *pResOut
2405** to a non-zero value otherwise *pResOut is set to zero. The return value
2406** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2407*/
drh734c9862008-11-28 15:37:20 +00002408static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2409 int rc = SQLITE_OK;
2410 int reserved = 0;
2411 unixFile *pFile = (unixFile*)id;
2412
2413 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2414
2415 assert( pFile );
2416
2417 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002418 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002419 reserved = 1;
2420 }
2421
2422 /* Otherwise see if some other process holds it. */
2423 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002424 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002425 struct stat statBuf;
2426
2427 if( sem_trywait(pSem)==-1 ){
2428 int tErrno = errno;
2429 if( EAGAIN != tErrno ){
2430 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2431 pFile->lastErrno = tErrno;
2432 } else {
2433 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002434 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002435 }
2436 }else{
2437 /* we could have it if we want it */
2438 sem_post(pSem);
2439 }
2440 }
drh308c2a52010-05-14 11:30:18 +00002441 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002442
2443 *pResOut = reserved;
2444 return rc;
2445}
2446
drh6b9d6dd2008-12-03 19:34:47 +00002447/*
drh308c2a52010-05-14 11:30:18 +00002448** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002449** of the following:
2450**
2451** (1) SHARED_LOCK
2452** (2) RESERVED_LOCK
2453** (3) PENDING_LOCK
2454** (4) EXCLUSIVE_LOCK
2455**
2456** Sometimes when requesting one lock state, additional lock states
2457** are inserted in between. The locking might fail on one of the later
2458** transitions leaving the lock state different from what it started but
2459** still short of its goal. The following chart shows the allowed
2460** transitions and the inserted intermediate states:
2461**
2462** UNLOCKED -> SHARED
2463** SHARED -> RESERVED
2464** SHARED -> (PENDING) -> EXCLUSIVE
2465** RESERVED -> (PENDING) -> EXCLUSIVE
2466** PENDING -> EXCLUSIVE
2467**
2468** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2469** lock states in the sqlite3_file structure, but all locks SHARED or
2470** above are really EXCLUSIVE locks and exclude all other processes from
2471** access the file.
2472**
2473** This routine will only increase a lock. Use the sqlite3OsUnlock()
2474** routine to lower a locking level.
2475*/
drh308c2a52010-05-14 11:30:18 +00002476static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002477 unixFile *pFile = (unixFile*)id;
2478 int fd;
drh8af6c222010-05-14 12:43:01 +00002479 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002480 int rc = SQLITE_OK;
2481
2482 /* if we already have a lock, it is exclusive.
2483 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002484 if (pFile->eFileLock > NO_LOCK) {
2485 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002486 rc = SQLITE_OK;
2487 goto sem_end_lock;
2488 }
2489
2490 /* lock semaphore now but bail out when already locked. */
2491 if( sem_trywait(pSem)==-1 ){
2492 rc = SQLITE_BUSY;
2493 goto sem_end_lock;
2494 }
2495
2496 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002497 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002498
2499 sem_end_lock:
2500 return rc;
2501}
2502
drh6b9d6dd2008-12-03 19:34:47 +00002503/*
drh308c2a52010-05-14 11:30:18 +00002504** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002505** must be either NO_LOCK or SHARED_LOCK.
2506**
2507** If the locking level of the file descriptor is already at or below
2508** the requested locking level, this routine is a no-op.
2509*/
drh308c2a52010-05-14 11:30:18 +00002510static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002511 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002512 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002513
2514 assert( pFile );
2515 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002516 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002517 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002518 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002519
2520 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002521 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002522 return SQLITE_OK;
2523 }
2524
2525 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002526 if (eFileLock==SHARED_LOCK) {
2527 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002528 return SQLITE_OK;
2529 }
2530
2531 /* no, really unlock. */
2532 if ( sem_post(pSem)==-1 ) {
2533 int rc, tErrno = errno;
2534 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2535 if( IS_LOCK_ERROR(rc) ){
2536 pFile->lastErrno = tErrno;
2537 }
2538 return rc;
2539 }
drh308c2a52010-05-14 11:30:18 +00002540 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002541 return SQLITE_OK;
2542}
2543
2544/*
2545 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002546 */
drh734c9862008-11-28 15:37:20 +00002547static int semClose(sqlite3_file *id) {
2548 if( id ){
2549 unixFile *pFile = (unixFile*)id;
2550 semUnlock(id, NO_LOCK);
2551 assert( pFile );
2552 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002553 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002554 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002555 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002556 }
2557 return SQLITE_OK;
2558}
2559
2560#endif /* OS_VXWORKS */
2561/*
2562** Named semaphore locking is only available on VxWorks.
2563**
2564*************** End of the named semaphore lock implementation ****************
2565******************************************************************************/
2566
2567
2568/******************************************************************************
2569*************************** Begin AFP Locking *********************************
2570**
2571** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2572** on Apple Macintosh computers - both OS9 and OSX.
2573**
2574** Third-party implementations of AFP are available. But this code here
2575** only works on OSX.
2576*/
2577
drhd2cb50b2009-01-09 21:41:17 +00002578#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002579/*
2580** The afpLockingContext structure contains all afp lock specific state
2581*/
drhbfe66312006-10-03 17:40:40 +00002582typedef struct afpLockingContext afpLockingContext;
2583struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002584 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002585 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002586};
2587
2588struct ByteRangeLockPB2
2589{
2590 unsigned long long offset; /* offset to first byte to lock */
2591 unsigned long long length; /* nbr of bytes to lock */
2592 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2593 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2594 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2595 int fd; /* file desc to assoc this lock with */
2596};
2597
drhfd131da2007-08-07 17:13:03 +00002598#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002599
drh6b9d6dd2008-12-03 19:34:47 +00002600/*
2601** This is a utility for setting or clearing a bit-range lock on an
2602** AFP filesystem.
2603**
2604** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2605*/
2606static int afpSetLock(
2607 const char *path, /* Name of the file to be locked or unlocked */
2608 unixFile *pFile, /* Open file descriptor on path */
2609 unsigned long long offset, /* First byte to be locked */
2610 unsigned long long length, /* Number of bytes to lock */
2611 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002612){
drh6b9d6dd2008-12-03 19:34:47 +00002613 struct ByteRangeLockPB2 pb;
2614 int err;
drhbfe66312006-10-03 17:40:40 +00002615
2616 pb.unLockFlag = setLockFlag ? 0 : 1;
2617 pb.startEndFlag = 0;
2618 pb.offset = offset;
2619 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002620 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002621
drh308c2a52010-05-14 11:30:18 +00002622 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002623 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002624 offset, length));
drhbfe66312006-10-03 17:40:40 +00002625 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2626 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002627 int rc;
2628 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002629 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2630 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002631#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2632 rc = SQLITE_BUSY;
2633#else
drh734c9862008-11-28 15:37:20 +00002634 rc = sqliteErrorFromPosixError(tErrno,
2635 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002636#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002637 if( IS_LOCK_ERROR(rc) ){
2638 pFile->lastErrno = tErrno;
2639 }
2640 return rc;
drhbfe66312006-10-03 17:40:40 +00002641 } else {
aswift5b1a2562008-08-22 00:22:35 +00002642 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002643 }
2644}
2645
drh6b9d6dd2008-12-03 19:34:47 +00002646/*
2647** This routine checks if there is a RESERVED lock held on the specified
2648** file by this or any other process. If such a lock is held, set *pResOut
2649** to a non-zero value otherwise *pResOut is set to zero. The return value
2650** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2651*/
danielk1977e339d652008-06-28 11:23:00 +00002652static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002653 int rc = SQLITE_OK;
2654 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002655 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002656 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002657
aswift5b1a2562008-08-22 00:22:35 +00002658 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2659
2660 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002661 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002662 if( context->reserved ){
2663 *pResOut = 1;
2664 return SQLITE_OK;
2665 }
drh8af6c222010-05-14 12:43:01 +00002666 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002667
2668 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002669 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002670 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002671 }
2672
2673 /* Otherwise see if some other process holds it.
2674 */
aswift5b1a2562008-08-22 00:22:35 +00002675 if( !reserved ){
2676 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002677 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002678 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002679 /* if we succeeded in taking the reserved lock, unlock it to restore
2680 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002681 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002682 } else {
2683 /* if we failed to get the lock then someone else must have it */
2684 reserved = 1;
2685 }
2686 if( IS_LOCK_ERROR(lrc) ){
2687 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002688 }
2689 }
drhbfe66312006-10-03 17:40:40 +00002690
drh7ed97b92010-01-20 13:07:21 +00002691 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002692 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002693
2694 *pResOut = reserved;
2695 return rc;
drhbfe66312006-10-03 17:40:40 +00002696}
2697
drh6b9d6dd2008-12-03 19:34:47 +00002698/*
drh308c2a52010-05-14 11:30:18 +00002699** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002700** of the following:
2701**
2702** (1) SHARED_LOCK
2703** (2) RESERVED_LOCK
2704** (3) PENDING_LOCK
2705** (4) EXCLUSIVE_LOCK
2706**
2707** Sometimes when requesting one lock state, additional lock states
2708** are inserted in between. The locking might fail on one of the later
2709** transitions leaving the lock state different from what it started but
2710** still short of its goal. The following chart shows the allowed
2711** transitions and the inserted intermediate states:
2712**
2713** UNLOCKED -> SHARED
2714** SHARED -> RESERVED
2715** SHARED -> (PENDING) -> EXCLUSIVE
2716** RESERVED -> (PENDING) -> EXCLUSIVE
2717** PENDING -> EXCLUSIVE
2718**
2719** This routine will only increase a lock. Use the sqlite3OsUnlock()
2720** routine to lower a locking level.
2721*/
drh308c2a52010-05-14 11:30:18 +00002722static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002723 int rc = SQLITE_OK;
2724 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002725 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002726 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002727
2728 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002729 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2730 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002731 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002732
drhbfe66312006-10-03 17:40:40 +00002733 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002734 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002735 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002736 */
drh308c2a52010-05-14 11:30:18 +00002737 if( pFile->eFileLock>=eFileLock ){
2738 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2739 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002740 return SQLITE_OK;
2741 }
2742
2743 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002744 ** (1) We never move from unlocked to anything higher than shared lock.
2745 ** (2) SQLite never explicitly requests a pendig lock.
2746 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002747 */
drh308c2a52010-05-14 11:30:18 +00002748 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2749 assert( eFileLock!=PENDING_LOCK );
2750 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002751
drh8af6c222010-05-14 12:43:01 +00002752 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002753 */
drh6c7d5c52008-11-21 20:32:33 +00002754 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002755 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002756
2757 /* If some thread using this PID has a lock via a different unixFile*
2758 ** handle that precludes the requested lock, return BUSY.
2759 */
drh8af6c222010-05-14 12:43:01 +00002760 if( (pFile->eFileLock!=pInode->eFileLock &&
2761 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002762 ){
2763 rc = SQLITE_BUSY;
2764 goto afp_end_lock;
2765 }
2766
2767 /* If a SHARED lock is requested, and some thread using this PID already
2768 ** has a SHARED or RESERVED lock, then increment reference counts and
2769 ** return SQLITE_OK.
2770 */
drh308c2a52010-05-14 11:30:18 +00002771 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002772 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002773 assert( eFileLock==SHARED_LOCK );
2774 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002775 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002776 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002777 pInode->nShared++;
2778 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002779 goto afp_end_lock;
2780 }
drhbfe66312006-10-03 17:40:40 +00002781
2782 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002783 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2784 ** be released.
2785 */
drh308c2a52010-05-14 11:30:18 +00002786 if( eFileLock==SHARED_LOCK
2787 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002788 ){
2789 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002790 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002791 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002792 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002793 goto afp_end_lock;
2794 }
2795 }
2796
2797 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002798 ** operating system calls for the specified lock.
2799 */
drh308c2a52010-05-14 11:30:18 +00002800 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002801 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002802 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002803
drh8af6c222010-05-14 12:43:01 +00002804 assert( pInode->nShared==0 );
2805 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002806
2807 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002808 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002809 /* note that the quality of the randomness doesn't matter that much */
2810 lk = random();
drh8af6c222010-05-14 12:43:01 +00002811 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002812 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002813 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002814 if( IS_LOCK_ERROR(lrc1) ){
2815 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002816 }
aswift5b1a2562008-08-22 00:22:35 +00002817 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002818 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002819
aswift5b1a2562008-08-22 00:22:35 +00002820 if( IS_LOCK_ERROR(lrc1) ) {
2821 pFile->lastErrno = lrc1Errno;
2822 rc = lrc1;
2823 goto afp_end_lock;
2824 } else if( IS_LOCK_ERROR(lrc2) ){
2825 rc = lrc2;
2826 goto afp_end_lock;
2827 } else if( lrc1 != SQLITE_OK ) {
2828 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002829 } else {
drh308c2a52010-05-14 11:30:18 +00002830 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002831 pInode->nLock++;
2832 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002833 }
drh8af6c222010-05-14 12:43:01 +00002834 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002835 /* We are trying for an exclusive lock but another thread in this
2836 ** same process is still holding a shared lock. */
2837 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002838 }else{
2839 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2840 ** assumed that there is a SHARED or greater lock on the file
2841 ** already.
2842 */
2843 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002844 assert( 0!=pFile->eFileLock );
2845 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002846 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002847 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002848 if( !failed ){
2849 context->reserved = 1;
2850 }
drhbfe66312006-10-03 17:40:40 +00002851 }
drh308c2a52010-05-14 11:30:18 +00002852 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002853 /* Acquire an EXCLUSIVE lock */
2854
2855 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002856 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002857 */
drh6b9d6dd2008-12-03 19:34:47 +00002858 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002859 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002860 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002861 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002862 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002863 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002864 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002865 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002866 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2867 ** a critical I/O error
2868 */
2869 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2870 SQLITE_IOERR_LOCK;
2871 goto afp_end_lock;
2872 }
2873 }else{
aswift5b1a2562008-08-22 00:22:35 +00002874 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002875 }
2876 }
aswift5b1a2562008-08-22 00:22:35 +00002877 if( failed ){
2878 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002879 }
2880 }
2881
2882 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002883 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002884 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002885 }else if( eFileLock==EXCLUSIVE_LOCK ){
2886 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002887 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002888 }
2889
2890afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002891 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002892 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2893 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002894 return rc;
2895}
2896
2897/*
drh308c2a52010-05-14 11:30:18 +00002898** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002899** must be either NO_LOCK or SHARED_LOCK.
2900**
2901** If the locking level of the file descriptor is already at or below
2902** the requested locking level, this routine is a no-op.
2903*/
drh308c2a52010-05-14 11:30:18 +00002904static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002905 int rc = SQLITE_OK;
2906 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002907 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002908 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2909 int skipShared = 0;
2910#ifdef SQLITE_TEST
2911 int h = pFile->h;
2912#endif
drhbfe66312006-10-03 17:40:40 +00002913
2914 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002915 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002916 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002917 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002918
drh308c2a52010-05-14 11:30:18 +00002919 assert( eFileLock<=SHARED_LOCK );
2920 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002921 return SQLITE_OK;
2922 }
drh6c7d5c52008-11-21 20:32:33 +00002923 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002924 pInode = pFile->pInode;
2925 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002926 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002927 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002928 SimulateIOErrorBenign(1);
2929 SimulateIOError( h=(-1) )
2930 SimulateIOErrorBenign(0);
2931
drhd3d8c042012-05-29 17:02:40 +00002932#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002933 /* When reducing a lock such that other processes can start
2934 ** reading the database file again, make sure that the
2935 ** transaction counter was updated if any part of the database
2936 ** file changed. If the transaction counter is not updated,
2937 ** other connections to the same file might not realize that
2938 ** the file has changed and hence might not know to flush their
2939 ** cache. The use of a stale cache can lead to database corruption.
2940 */
2941 assert( pFile->inNormalWrite==0
2942 || pFile->dbUpdate==0
2943 || pFile->transCntrChng==1 );
2944 pFile->inNormalWrite = 0;
2945#endif
aswiftaebf4132008-11-21 00:10:35 +00002946
drh308c2a52010-05-14 11:30:18 +00002947 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002948 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002949 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002950 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002951 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002952 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2953 } else {
2954 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002955 }
2956 }
drh308c2a52010-05-14 11:30:18 +00002957 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002958 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002959 }
drh308c2a52010-05-14 11:30:18 +00002960 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002961 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2962 if( !rc ){
2963 context->reserved = 0;
2964 }
aswiftaebf4132008-11-21 00:10:35 +00002965 }
drh8af6c222010-05-14 12:43:01 +00002966 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2967 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002968 }
aswiftaebf4132008-11-21 00:10:35 +00002969 }
drh308c2a52010-05-14 11:30:18 +00002970 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002971
drh7ed97b92010-01-20 13:07:21 +00002972 /* Decrement the shared lock counter. Release the lock using an
2973 ** OS call only when all threads in this same process have released
2974 ** the lock.
2975 */
drh8af6c222010-05-14 12:43:01 +00002976 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2977 pInode->nShared--;
2978 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002979 SimulateIOErrorBenign(1);
2980 SimulateIOError( h=(-1) )
2981 SimulateIOErrorBenign(0);
2982 if( !skipShared ){
2983 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2984 }
2985 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002986 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002987 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002988 }
2989 }
2990 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002991 pInode->nLock--;
2992 assert( pInode->nLock>=0 );
2993 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002994 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002995 }
2996 }
drhbfe66312006-10-03 17:40:40 +00002997 }
drh7ed97b92010-01-20 13:07:21 +00002998
drh6c7d5c52008-11-21 20:32:33 +00002999 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003000 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003001 return rc;
3002}
3003
3004/*
drh339eb0b2008-03-07 15:34:11 +00003005** Close a file & cleanup AFP specific locking context
3006*/
danielk1977e339d652008-06-28 11:23:00 +00003007static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003008 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003009 if( id ){
3010 unixFile *pFile = (unixFile*)id;
3011 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003012 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003013 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003014 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003015 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003016 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003017 ** the last lock is cleared.
3018 */
dan08da86a2009-08-21 17:18:03 +00003019 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003020 }
danb0ac3e32010-06-16 10:55:42 +00003021 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003022 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003023 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003024 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003025 }
drh7ed97b92010-01-20 13:07:21 +00003026 return rc;
drhbfe66312006-10-03 17:40:40 +00003027}
3028
drhd2cb50b2009-01-09 21:41:17 +00003029#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003030/*
3031** The code above is the AFP lock implementation. The code is specific
3032** to MacOSX and does not work on other unix platforms. No alternative
3033** is available. If you don't compile for a mac, then the "unix-afp"
3034** VFS is not available.
3035**
3036********************* End of the AFP lock implementation **********************
3037******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003038
drh7ed97b92010-01-20 13:07:21 +00003039/******************************************************************************
3040*************************** Begin NFS Locking ********************************/
3041
3042#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3043/*
drh308c2a52010-05-14 11:30:18 +00003044 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003045 ** must be either NO_LOCK or SHARED_LOCK.
3046 **
3047 ** If the locking level of the file descriptor is already at or below
3048 ** the requested locking level, this routine is a no-op.
3049 */
drh308c2a52010-05-14 11:30:18 +00003050static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003051 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003052}
3053
3054#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3055/*
3056** The code above is the NFS lock implementation. The code is specific
3057** to MacOSX and does not work on other unix platforms. No alternative
3058** is available.
3059**
3060********************* End of the NFS lock implementation **********************
3061******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003062
3063/******************************************************************************
3064**************** Non-locking sqlite3_file methods *****************************
3065**
3066** The next division contains implementations for all methods of the
3067** sqlite3_file object other than the locking methods. The locking
3068** methods were defined in divisions above (one locking method per
3069** division). Those methods that are common to all locking modes
3070** are gather together into this division.
3071*/
drhbfe66312006-10-03 17:40:40 +00003072
3073/*
drh734c9862008-11-28 15:37:20 +00003074** Seek to the offset passed as the second argument, then read cnt
3075** bytes into pBuf. Return the number of bytes actually read.
3076**
3077** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3078** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3079** one system to another. Since SQLite does not define USE_PREAD
3080** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3081** See tickets #2741 and #2681.
3082**
3083** To avoid stomping the errno value on a failed read the lastErrno value
3084** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003085*/
drh734c9862008-11-28 15:37:20 +00003086static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3087 int got;
drh58024642011-11-07 18:16:00 +00003088 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003089#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003090 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003091#endif
drh734c9862008-11-28 15:37:20 +00003092 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003093 assert( cnt==(cnt&0x1ffff) );
3094 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003095 do{
drh734c9862008-11-28 15:37:20 +00003096#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003097 got = osPread(id->h, pBuf, cnt, offset);
3098 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003099#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003100 got = osPread64(id->h, pBuf, cnt, offset);
3101 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003102#else
drh58024642011-11-07 18:16:00 +00003103 newOffset = lseek(id->h, offset, SEEK_SET);
3104 SimulateIOError( newOffset-- );
3105 if( newOffset!=offset ){
3106 if( newOffset == -1 ){
3107 ((unixFile*)id)->lastErrno = errno;
3108 }else{
drhf2f105d2012-08-20 15:53:54 +00003109 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003110 }
3111 return -1;
drh734c9862008-11-28 15:37:20 +00003112 }
drh58024642011-11-07 18:16:00 +00003113 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003114#endif
drh58024642011-11-07 18:16:00 +00003115 if( got==cnt ) break;
3116 if( got<0 ){
3117 if( errno==EINTR ){ got = 1; continue; }
3118 prior = 0;
3119 ((unixFile*)id)->lastErrno = errno;
3120 break;
3121 }else if( got>0 ){
3122 cnt -= got;
3123 offset += got;
3124 prior += got;
3125 pBuf = (void*)(got + (char*)pBuf);
3126 }
3127 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003128 TIMER_END;
drh58024642011-11-07 18:16:00 +00003129 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3130 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3131 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003132}
3133
3134/*
drh734c9862008-11-28 15:37:20 +00003135** Read data from a file into a buffer. Return SQLITE_OK if all
3136** bytes were read successfully and SQLITE_IOERR if anything goes
3137** wrong.
drh339eb0b2008-03-07 15:34:11 +00003138*/
drh734c9862008-11-28 15:37:20 +00003139static int unixRead(
3140 sqlite3_file *id,
3141 void *pBuf,
3142 int amt,
3143 sqlite3_int64 offset
3144){
dan08da86a2009-08-21 17:18:03 +00003145 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003146 int got;
3147 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003148 assert( offset>=0 );
3149 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003150
dan08da86a2009-08-21 17:18:03 +00003151 /* If this is a database file (not a journal, master-journal or temp
3152 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003153#if 0
dane946c392009-08-22 11:39:46 +00003154 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003155 || offset>=PENDING_BYTE+512
3156 || offset+amt<=PENDING_BYTE
3157 );
dan7c246102010-04-12 19:00:29 +00003158#endif
drh08c6d442009-02-09 17:34:07 +00003159
drh9b4c59f2013-04-15 17:03:42 +00003160#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003161 /* Deal with as much of this read request as possible by transfering
3162 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003163 if( offset<pFile->mmapSize ){
3164 if( offset+amt <= pFile->mmapSize ){
3165 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3166 return SQLITE_OK;
3167 }else{
3168 int nCopy = pFile->mmapSize - offset;
3169 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3170 pBuf = &((u8 *)pBuf)[nCopy];
3171 amt -= nCopy;
3172 offset += nCopy;
3173 }
3174 }
drh6e0b6d52013-04-09 16:19:20 +00003175#endif
danf23da962013-03-23 21:00:41 +00003176
dan08da86a2009-08-21 17:18:03 +00003177 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003178 if( got==amt ){
3179 return SQLITE_OK;
3180 }else if( got<0 ){
3181 /* lastErrno set by seekAndRead */
3182 return SQLITE_IOERR_READ;
3183 }else{
dan08da86a2009-08-21 17:18:03 +00003184 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003185 /* Unread parts of the buffer must be zero-filled */
3186 memset(&((char*)pBuf)[got], 0, amt-got);
3187 return SQLITE_IOERR_SHORT_READ;
3188 }
3189}
3190
3191/*
dan47a2b4a2013-04-26 16:09:29 +00003192** Attempt to seek the file-descriptor passed as the first argument to
3193** absolute offset iOff, then attempt to write nBuf bytes of data from
3194** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3195** return the actual number of bytes written (which may be less than
3196** nBuf).
3197*/
3198static int seekAndWriteFd(
3199 int fd, /* File descriptor to write to */
3200 i64 iOff, /* File offset to begin writing at */
3201 const void *pBuf, /* Copy data from this buffer to the file */
3202 int nBuf, /* Size of buffer pBuf in bytes */
3203 int *piErrno /* OUT: Error number if error occurs */
3204){
3205 int rc = 0; /* Value returned by system call */
3206
3207 assert( nBuf==(nBuf&0x1ffff) );
3208 nBuf &= 0x1ffff;
3209 TIMER_START;
3210
3211#if defined(USE_PREAD)
3212 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3213#elif defined(USE_PREAD64)
3214 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3215#else
3216 do{
3217 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3218 SimulateIOError( iSeek-- );
3219
3220 if( iSeek!=iOff ){
3221 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3222 return -1;
3223 }
3224 rc = osWrite(fd, pBuf, nBuf);
3225 }while( rc<0 && errno==EINTR );
3226#endif
3227
3228 TIMER_END;
3229 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3230
3231 if( rc<0 && piErrno ) *piErrno = errno;
3232 return rc;
3233}
3234
3235
3236/*
drh734c9862008-11-28 15:37:20 +00003237** Seek to the offset in id->offset then read cnt bytes into pBuf.
3238** Return the number of bytes actually read. Update the offset.
3239**
3240** To avoid stomping the errno value on a failed write the lastErrno value
3241** is set before returning.
3242*/
3243static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003244 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003245}
3246
3247
3248/*
3249** Write data from a buffer into a file. Return SQLITE_OK on success
3250** or some other error code on failure.
3251*/
3252static int unixWrite(
3253 sqlite3_file *id,
3254 const void *pBuf,
3255 int amt,
3256 sqlite3_int64 offset
3257){
dan08da86a2009-08-21 17:18:03 +00003258 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003259 int wrote = 0;
3260 assert( id );
3261 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003262
dan08da86a2009-08-21 17:18:03 +00003263 /* If this is a database file (not a journal, master-journal or temp
3264 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003265#if 0
dane946c392009-08-22 11:39:46 +00003266 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003267 || offset>=PENDING_BYTE+512
3268 || offset+amt<=PENDING_BYTE
3269 );
dan7c246102010-04-12 19:00:29 +00003270#endif
drh08c6d442009-02-09 17:34:07 +00003271
drhd3d8c042012-05-29 17:02:40 +00003272#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003273 /* If we are doing a normal write to a database file (as opposed to
3274 ** doing a hot-journal rollback or a write to some file other than a
3275 ** normal database file) then record the fact that the database
3276 ** has changed. If the transaction counter is modified, record that
3277 ** fact too.
3278 */
dan08da86a2009-08-21 17:18:03 +00003279 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003280 pFile->dbUpdate = 1; /* The database has been modified */
3281 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003282 int rc;
drh8f941bc2009-01-14 23:03:40 +00003283 char oldCntr[4];
3284 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003285 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003286 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003287 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003288 pFile->transCntrChng = 1; /* The transaction counter has changed */
3289 }
3290 }
3291 }
3292#endif
3293
drh9b4c59f2013-04-15 17:03:42 +00003294#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003295 /* Deal with as much of this write request as possible by transfering
3296 ** data from the memory mapping using memcpy(). */
3297 if( offset<pFile->mmapSize ){
3298 if( offset+amt <= pFile->mmapSize ){
3299 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3300 return SQLITE_OK;
3301 }else{
3302 int nCopy = pFile->mmapSize - offset;
3303 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3304 pBuf = &((u8 *)pBuf)[nCopy];
3305 amt -= nCopy;
3306 offset += nCopy;
3307 }
3308 }
drh6e0b6d52013-04-09 16:19:20 +00003309#endif
danf23da962013-03-23 21:00:41 +00003310
dan08da86a2009-08-21 17:18:03 +00003311 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003312 amt -= wrote;
3313 offset += wrote;
3314 pBuf = &((char*)pBuf)[wrote];
3315 }
3316 SimulateIOError(( wrote=(-1), amt=1 ));
3317 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003318
drh734c9862008-11-28 15:37:20 +00003319 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003320 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003321 /* lastErrno set by seekAndWrite */
3322 return SQLITE_IOERR_WRITE;
3323 }else{
dan08da86a2009-08-21 17:18:03 +00003324 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003325 return SQLITE_FULL;
3326 }
3327 }
dan6e09d692010-07-27 18:34:15 +00003328
drh734c9862008-11-28 15:37:20 +00003329 return SQLITE_OK;
3330}
3331
3332#ifdef SQLITE_TEST
3333/*
3334** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003335** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003336*/
3337int sqlite3_sync_count = 0;
3338int sqlite3_fullsync_count = 0;
3339#endif
3340
3341/*
drh89240432009-03-25 01:06:01 +00003342** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003343** Others do no. To be safe, we will stick with the (slightly slower)
3344** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003345** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003346*/
drh20f8e132011-08-31 21:01:55 +00003347#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003348# define fdatasync fsync
3349#endif
3350
3351/*
3352** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3353** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3354** only available on Mac OS X. But that could change.
3355*/
3356#ifdef F_FULLFSYNC
3357# define HAVE_FULLFSYNC 1
3358#else
3359# define HAVE_FULLFSYNC 0
3360#endif
3361
3362
3363/*
3364** The fsync() system call does not work as advertised on many
3365** unix systems. The following procedure is an attempt to make
3366** it work better.
3367**
3368** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3369** for testing when we want to run through the test suite quickly.
3370** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3371** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3372** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003373**
3374** SQLite sets the dataOnly flag if the size of the file is unchanged.
3375** The idea behind dataOnly is that it should only write the file content
3376** to disk, not the inode. We only set dataOnly if the file size is
3377** unchanged since the file size is part of the inode. However,
3378** Ted Ts'o tells us that fdatasync() will also write the inode if the
3379** file size has changed. The only real difference between fdatasync()
3380** and fsync(), Ted tells us, is that fdatasync() will not flush the
3381** inode if the mtime or owner or other inode attributes have changed.
3382** We only care about the file size, not the other file attributes, so
3383** as far as SQLite is concerned, an fdatasync() is always adequate.
3384** So, we always use fdatasync() if it is available, regardless of
3385** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003386*/
3387static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003388 int rc;
drh734c9862008-11-28 15:37:20 +00003389
3390 /* The following "ifdef/elif/else/" block has the same structure as
3391 ** the one below. It is replicated here solely to avoid cluttering
3392 ** up the real code with the UNUSED_PARAMETER() macros.
3393 */
3394#ifdef SQLITE_NO_SYNC
3395 UNUSED_PARAMETER(fd);
3396 UNUSED_PARAMETER(fullSync);
3397 UNUSED_PARAMETER(dataOnly);
3398#elif HAVE_FULLFSYNC
3399 UNUSED_PARAMETER(dataOnly);
3400#else
3401 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003402 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003403#endif
3404
3405 /* Record the number of times that we do a normal fsync() and
3406 ** FULLSYNC. This is used during testing to verify that this procedure
3407 ** gets called with the correct arguments.
3408 */
3409#ifdef SQLITE_TEST
3410 if( fullSync ) sqlite3_fullsync_count++;
3411 sqlite3_sync_count++;
3412#endif
3413
3414 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3415 ** no-op
3416 */
3417#ifdef SQLITE_NO_SYNC
3418 rc = SQLITE_OK;
3419#elif HAVE_FULLFSYNC
3420 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003421 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003422 }else{
3423 rc = 1;
3424 }
3425 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003426 ** It shouldn't be possible for fullfsync to fail on the local
3427 ** file system (on OSX), so failure indicates that FULLFSYNC
3428 ** isn't supported for this file system. So, attempt an fsync
3429 ** and (for now) ignore the overhead of a superfluous fcntl call.
3430 ** It'd be better to detect fullfsync support once and avoid
3431 ** the fcntl call every time sync is called.
3432 */
drh734c9862008-11-28 15:37:20 +00003433 if( rc ) rc = fsync(fd);
3434
drh7ed97b92010-01-20 13:07:21 +00003435#elif defined(__APPLE__)
3436 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3437 ** so currently we default to the macro that redefines fdatasync to fsync
3438 */
3439 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003440#else
drh0b647ff2009-03-21 14:41:04 +00003441 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003442#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003443 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003444 rc = fsync(fd);
3445 }
drh0b647ff2009-03-21 14:41:04 +00003446#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003447#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3448
3449 if( OS_VXWORKS && rc!= -1 ){
3450 rc = 0;
3451 }
chw97185482008-11-17 08:05:31 +00003452 return rc;
drhbfe66312006-10-03 17:40:40 +00003453}
3454
drh734c9862008-11-28 15:37:20 +00003455/*
drh0059eae2011-08-08 23:48:40 +00003456** Open a file descriptor to the directory containing file zFilename.
3457** If successful, *pFd is set to the opened file descriptor and
3458** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3459** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3460** value.
3461**
drh90315a22011-08-10 01:52:12 +00003462** The directory file descriptor is used for only one thing - to
3463** fsync() a directory to make sure file creation and deletion events
3464** are flushed to disk. Such fsyncs are not needed on newer
3465** journaling filesystems, but are required on older filesystems.
3466**
3467** This routine can be overridden using the xSetSysCall interface.
3468** The ability to override this routine was added in support of the
3469** chromium sandbox. Opening a directory is a security risk (we are
3470** told) so making it overrideable allows the chromium sandbox to
3471** replace this routine with a harmless no-op. To make this routine
3472** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3473** *pFd set to a negative number.
3474**
drh0059eae2011-08-08 23:48:40 +00003475** If SQLITE_OK is returned, the caller is responsible for closing
3476** the file descriptor *pFd using close().
3477*/
3478static int openDirectory(const char *zFilename, int *pFd){
3479 int ii;
3480 int fd = -1;
3481 char zDirname[MAX_PATHNAME+1];
3482
3483 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3484 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3485 if( ii>0 ){
3486 zDirname[ii] = '\0';
3487 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3488 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003489 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3490 }
3491 }
3492 *pFd = fd;
3493 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3494}
3495
3496/*
drh734c9862008-11-28 15:37:20 +00003497** Make sure all writes to a particular file are committed to disk.
3498**
3499** If dataOnly==0 then both the file itself and its metadata (file
3500** size, access time, etc) are synced. If dataOnly!=0 then only the
3501** file data is synced.
3502**
3503** Under Unix, also make sure that the directory entry for the file
3504** has been created by fsync-ing the directory that contains the file.
3505** If we do not do this and we encounter a power failure, the directory
3506** entry for the journal might not exist after we reboot. The next
3507** SQLite to access the file will not know that the journal exists (because
3508** the directory entry for the journal was never created) and the transaction
3509** will not roll back - possibly leading to database corruption.
3510*/
3511static int unixSync(sqlite3_file *id, int flags){
3512 int rc;
3513 unixFile *pFile = (unixFile*)id;
3514
3515 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3516 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3517
3518 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3519 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3520 || (flags&0x0F)==SQLITE_SYNC_FULL
3521 );
3522
3523 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3524 ** line is to test that doing so does not cause any problems.
3525 */
3526 SimulateDiskfullError( return SQLITE_FULL );
3527
3528 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003529 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003530 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3531 SimulateIOError( rc=1 );
3532 if( rc ){
3533 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003534 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003535 }
drh0059eae2011-08-08 23:48:40 +00003536
3537 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003538 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003539 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003540 */
3541 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3542 int dirfd;
3543 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003544 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003545 rc = osOpenDirectory(pFile->zPath, &dirfd);
3546 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003547 full_fsync(dirfd, 0, 0);
3548 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003549 }else if( rc==SQLITE_CANTOPEN ){
3550 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003551 }
drh0059eae2011-08-08 23:48:40 +00003552 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003553 }
3554 return rc;
3555}
3556
3557/*
3558** Truncate an open file to a specified size
3559*/
3560static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003561 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003562 int rc;
dan6e09d692010-07-27 18:34:15 +00003563 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003564 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003565
3566 /* If the user has configured a chunk-size for this file, truncate the
3567 ** file so that it consists of an integer number of chunks (i.e. the
3568 ** actual file size after the operation may be larger than the requested
3569 ** size).
3570 */
drhb8af4b72012-04-05 20:04:39 +00003571 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003572 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3573 }
3574
drhff812312011-02-23 13:33:46 +00003575 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003576 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003577 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003578 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003579 }else{
drhd3d8c042012-05-29 17:02:40 +00003580#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003581 /* If we are doing a normal write to a database file (as opposed to
3582 ** doing a hot-journal rollback or a write to some file other than a
3583 ** normal database file) and we truncate the file to zero length,
3584 ** that effectively updates the change counter. This might happen
3585 ** when restoring a database using the backup API from a zero-length
3586 ** source.
3587 */
dan6e09d692010-07-27 18:34:15 +00003588 if( pFile->inNormalWrite && nByte==0 ){
3589 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003590 }
danf23da962013-03-23 21:00:41 +00003591#endif
danc0003312013-03-22 17:46:11 +00003592
3593 /* If the file was just truncated to a size smaller than the currently
3594 ** mapped region, reduce the effective mapping size as well. SQLite will
3595 ** use read() and write() to access data beyond this point from now on.
3596 */
3597 if( nByte<pFile->mmapSize ){
3598 pFile->mmapSize = nByte;
3599 }
drh3313b142009-11-06 04:13:18 +00003600
drh734c9862008-11-28 15:37:20 +00003601 return SQLITE_OK;
3602 }
3603}
3604
3605/*
3606** Determine the current size of a file in bytes
3607*/
3608static int unixFileSize(sqlite3_file *id, i64 *pSize){
3609 int rc;
3610 struct stat buf;
3611 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003612 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003613 SimulateIOError( rc=1 );
3614 if( rc!=0 ){
3615 ((unixFile*)id)->lastErrno = errno;
3616 return SQLITE_IOERR_FSTAT;
3617 }
3618 *pSize = buf.st_size;
3619
drh8af6c222010-05-14 12:43:01 +00003620 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003621 ** writes a single byte into that file in order to work around a bug
3622 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3623 ** layers, we need to report this file size as zero even though it is
3624 ** really 1. Ticket #3260.
3625 */
3626 if( *pSize==1 ) *pSize = 0;
3627
3628
3629 return SQLITE_OK;
3630}
3631
drhd2cb50b2009-01-09 21:41:17 +00003632#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003633/*
3634** Handler for proxy-locking file-control verbs. Defined below in the
3635** proxying locking division.
3636*/
3637static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003638#endif
drh715ff302008-12-03 22:32:44 +00003639
dan502019c2010-07-28 14:26:17 +00003640/*
3641** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003642** file-control operation. Enlarge the database to nBytes in size
3643** (rounded up to the next chunk-size). If the database is already
3644** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003645*/
3646static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003647 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003648 i64 nSize; /* Required file size */
3649 struct stat buf; /* Used to hold return values of fstat() */
3650
drh99ab3b12011-03-02 15:09:07 +00003651 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003652
3653 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3654 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003655
dan502019c2010-07-28 14:26:17 +00003656#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003657 /* The code below is handling the return value of osFallocate()
3658 ** correctly. posix_fallocate() is defined to "returns zero on success,
3659 ** or an error number on failure". See the manpage for details. */
3660 int err;
drhff812312011-02-23 13:33:46 +00003661 do{
dan661d71a2011-03-30 19:08:03 +00003662 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3663 }while( err==EINTR );
3664 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003665#else
3666 /* If the OS does not have posix_fallocate(), fake it. First use
3667 ** ftruncate() to set the file size, then write a single byte to
3668 ** the last byte in each block within the extended region. This
3669 ** is the same technique used by glibc to implement posix_fallocate()
3670 ** on systems that do not have a real fallocate() system call.
3671 */
3672 int nBlk = buf.st_blksize; /* File-system block size */
3673 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003674
drhff812312011-02-23 13:33:46 +00003675 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003676 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003677 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003678 }
3679 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003680 while( iWrite<nSize ){
3681 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3682 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003683 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003684 }
dan502019c2010-07-28 14:26:17 +00003685#endif
3686 }
3687 }
3688
drh9b4c59f2013-04-15 17:03:42 +00003689 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003690 int rc;
3691 if( pFile->szChunk<=0 ){
3692 if( robust_ftruncate(pFile->h, nByte) ){
3693 pFile->lastErrno = errno;
3694 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3695 }
3696 }
3697
3698 rc = unixMapfile(pFile, nByte);
3699 return rc;
3700 }
3701
dan502019c2010-07-28 14:26:17 +00003702 return SQLITE_OK;
3703}
danielk1977ad94b582007-08-20 06:44:22 +00003704
danielk1977e3026632004-06-22 11:29:02 +00003705/*
drhf12b3f62011-12-21 14:42:29 +00003706** If *pArg is inititially negative then this is a query. Set *pArg to
3707** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3708**
3709** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3710*/
3711static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3712 if( *pArg<0 ){
3713 *pArg = (pFile->ctrlFlags & mask)!=0;
3714 }else if( (*pArg)==0 ){
3715 pFile->ctrlFlags &= ~mask;
3716 }else{
3717 pFile->ctrlFlags |= mask;
3718 }
3719}
3720
drh696b33e2012-12-06 19:01:42 +00003721/* Forward declaration */
3722static int unixGetTempname(int nBuf, char *zBuf);
3723
drhf12b3f62011-12-21 14:42:29 +00003724/*
drh9e33c2c2007-08-31 18:34:59 +00003725** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003726*/
drhcc6bb3e2007-08-31 16:11:35 +00003727static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003728 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003729 switch( op ){
3730 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003731 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003732 return SQLITE_OK;
3733 }
drh7708e972008-11-29 00:56:52 +00003734 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003735 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003736 return SQLITE_OK;
3737 }
dan6e09d692010-07-27 18:34:15 +00003738 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003739 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003740 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003741 }
drh9ff27ec2010-05-19 19:26:05 +00003742 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003743 int rc;
3744 SimulateIOErrorBenign(1);
3745 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3746 SimulateIOErrorBenign(0);
3747 return rc;
drhf0b190d2011-07-26 16:03:07 +00003748 }
3749 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003750 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3751 return SQLITE_OK;
3752 }
drhcb15f352011-12-23 01:04:17 +00003753 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3754 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003755 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003756 }
drhde60fc22011-12-14 17:53:36 +00003757 case SQLITE_FCNTL_VFSNAME: {
3758 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3759 return SQLITE_OK;
3760 }
drh696b33e2012-12-06 19:01:42 +00003761 case SQLITE_FCNTL_TEMPFILENAME: {
3762 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3763 if( zTFile ){
3764 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3765 *(char**)pArg = zTFile;
3766 }
3767 return SQLITE_OK;
3768 }
drh9b4c59f2013-04-15 17:03:42 +00003769 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003770 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003771 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003772 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3773 newLimit = sqlite3GlobalConfig.mxMmap;
3774 }
3775 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003776 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003777 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003778 if( pFile->mmapSize>0 ){
3779 unixUnmapfile(pFile);
3780 rc = unixMapfile(pFile, -1);
3781 }
danbcb8a862013-04-08 15:30:41 +00003782 }
drh34e258c2013-05-23 01:40:53 +00003783 return rc;
danb2d3de32013-03-14 18:34:37 +00003784 }
drhd3d8c042012-05-29 17:02:40 +00003785#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003786 /* The pager calls this method to signal that it has done
3787 ** a rollback and that the database is therefore unchanged and
3788 ** it hence it is OK for the transaction change counter to be
3789 ** unchanged.
3790 */
3791 case SQLITE_FCNTL_DB_UNCHANGED: {
3792 ((unixFile*)id)->dbUpdate = 0;
3793 return SQLITE_OK;
3794 }
3795#endif
drhd2cb50b2009-01-09 21:41:17 +00003796#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003797 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003798 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003799 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003800 }
drhd2cb50b2009-01-09 21:41:17 +00003801#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003802 }
drh0b52b7d2011-01-26 19:46:22 +00003803 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003804}
3805
3806/*
danielk1977a3d4c882007-03-23 10:08:38 +00003807** Return the sector size in bytes of the underlying block device for
3808** the specified file. This is almost always 512 bytes, but may be
3809** larger for some devices.
3810**
3811** SQLite code assumes this function cannot fail. It also assumes that
3812** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003813** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003814** same for both.
3815*/
drh537dddf2012-10-26 13:46:24 +00003816#ifndef __QNXNTO__
3817static int unixSectorSize(sqlite3_file *NotUsed){
3818 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003819 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003820}
drh537dddf2012-10-26 13:46:24 +00003821#endif
3822
3823/*
3824** The following version of unixSectorSize() is optimized for QNX.
3825*/
3826#ifdef __QNXNTO__
3827#include <sys/dcmd_blk.h>
3828#include <sys/statvfs.h>
3829static int unixSectorSize(sqlite3_file *id){
3830 unixFile *pFile = (unixFile*)id;
3831 if( pFile->sectorSize == 0 ){
3832 struct statvfs fsInfo;
3833
3834 /* Set defaults for non-supported filesystems */
3835 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3836 pFile->deviceCharacteristics = 0;
3837 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3838 return pFile->sectorSize;
3839 }
3840
3841 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3842 pFile->sectorSize = fsInfo.f_bsize;
3843 pFile->deviceCharacteristics =
3844 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3845 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3846 ** the write succeeds */
3847 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3848 ** so it is ordered */
3849 0;
3850 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3851 pFile->sectorSize = fsInfo.f_bsize;
3852 pFile->deviceCharacteristics =
3853 /* etfs cluster size writes are atomic */
3854 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3855 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3856 ** the write succeeds */
3857 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3858 ** so it is ordered */
3859 0;
3860 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3861 pFile->sectorSize = fsInfo.f_bsize;
3862 pFile->deviceCharacteristics =
3863 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3864 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3865 ** the write succeeds */
3866 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3867 ** so it is ordered */
3868 0;
3869 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3870 pFile->sectorSize = fsInfo.f_bsize;
3871 pFile->deviceCharacteristics =
3872 /* full bitset of atomics from max sector size and smaller */
3873 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3874 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3875 ** so it is ordered */
3876 0;
3877 }else if( strstr(fsInfo.f_basetype, "dos") ){
3878 pFile->sectorSize = fsInfo.f_bsize;
3879 pFile->deviceCharacteristics =
3880 /* full bitset of atomics from max sector size and smaller */
3881 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3882 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3883 ** so it is ordered */
3884 0;
3885 }else{
3886 pFile->deviceCharacteristics =
3887 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3888 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3889 ** the write succeeds */
3890 0;
3891 }
3892 }
3893 /* Last chance verification. If the sector size isn't a multiple of 512
3894 ** then it isn't valid.*/
3895 if( pFile->sectorSize % 512 != 0 ){
3896 pFile->deviceCharacteristics = 0;
3897 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3898 }
3899 return pFile->sectorSize;
3900}
3901#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003902
danielk197790949c22007-08-17 16:50:38 +00003903/*
drhf12b3f62011-12-21 14:42:29 +00003904** Return the device characteristics for the file.
3905**
drhcb15f352011-12-23 01:04:17 +00003906** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3907** However, that choice is contraversial since technically the underlying
3908** file system does not always provide powersafe overwrites. (In other
3909** words, after a power-loss event, parts of the file that were never
3910** written might end up being altered.) However, non-PSOW behavior is very,
3911** very rare. And asserting PSOW makes a large reduction in the amount
3912** of required I/O for journaling, since a lot of padding is eliminated.
3913** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3914** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003915*/
drhf12b3f62011-12-21 14:42:29 +00003916static int unixDeviceCharacteristics(sqlite3_file *id){
3917 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003918 int rc = 0;
3919#ifdef __QNXNTO__
3920 if( p->sectorSize==0 ) unixSectorSize(id);
3921 rc = p->deviceCharacteristics;
3922#endif
drhcb15f352011-12-23 01:04:17 +00003923 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003924 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003925 }
drh537dddf2012-10-26 13:46:24 +00003926 return rc;
danielk197762079062007-08-15 17:08:46 +00003927}
3928
drhd9e5c4f2010-05-12 18:01:39 +00003929#ifndef SQLITE_OMIT_WAL
3930
3931
3932/*
drhd91c68f2010-05-14 14:52:25 +00003933** Object used to represent an shared memory buffer.
3934**
3935** When multiple threads all reference the same wal-index, each thread
3936** has its own unixShm object, but they all point to a single instance
3937** of this unixShmNode object. In other words, each wal-index is opened
3938** only once per process.
3939**
3940** Each unixShmNode object is connected to a single unixInodeInfo object.
3941** We could coalesce this object into unixInodeInfo, but that would mean
3942** every open file that does not use shared memory (in other words, most
3943** open files) would have to carry around this extra information. So
3944** the unixInodeInfo object contains a pointer to this unixShmNode object
3945** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003946**
3947** unixMutexHeld() must be true when creating or destroying
3948** this object or while reading or writing the following fields:
3949**
3950** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003951**
3952** The following fields are read-only after the object is created:
3953**
3954** fid
3955** zFilename
3956**
drhd91c68f2010-05-14 14:52:25 +00003957** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003958** unixMutexHeld() is true when reading or writing any other field
3959** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003960*/
drhd91c68f2010-05-14 14:52:25 +00003961struct unixShmNode {
3962 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003963 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003964 char *zFilename; /* Name of the mmapped file */
3965 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003966 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003967 u16 nRegion; /* Size of array apRegion */
3968 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003969 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003970 int nRef; /* Number of unixShm objects pointing to this */
3971 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003972#ifdef SQLITE_DEBUG
3973 u8 exclMask; /* Mask of exclusive locks held */
3974 u8 sharedMask; /* Mask of shared locks held */
3975 u8 nextShmId; /* Next available unixShm.id value */
3976#endif
3977};
3978
3979/*
drhd9e5c4f2010-05-12 18:01:39 +00003980** Structure used internally by this VFS to record the state of an
3981** open shared memory connection.
3982**
drhd91c68f2010-05-14 14:52:25 +00003983** The following fields are initialized when this object is created and
3984** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003985**
drhd91c68f2010-05-14 14:52:25 +00003986** unixShm.pFile
3987** unixShm.id
3988**
3989** All other fields are read/write. The unixShm.pFile->mutex must be held
3990** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003991*/
3992struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003993 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3994 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003995 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003996 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003997 u16 sharedMask; /* Mask of shared locks held */
3998 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003999};
4000
4001/*
drhd9e5c4f2010-05-12 18:01:39 +00004002** Constants used for locking
4003*/
drhbd9676c2010-06-23 17:58:38 +00004004#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004005#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004006
drhd9e5c4f2010-05-12 18:01:39 +00004007/*
drh73b64e42010-05-30 19:55:15 +00004008** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004009**
4010** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4011** otherwise.
4012*/
4013static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004014 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4015 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004016 int ofst, /* First byte of the locking range */
4017 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004018){
4019 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004020 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004021
drhd91c68f2010-05-14 14:52:25 +00004022 /* Access to the unixShmNode object is serialized by the caller */
4023 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004024
drh73b64e42010-05-30 19:55:15 +00004025 /* Shared locks never span more than one byte */
4026 assert( n==1 || lockType!=F_RDLCK );
4027
4028 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004029 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004030
drh3cb93392011-03-12 18:10:44 +00004031 if( pShmNode->h>=0 ){
4032 /* Initialize the locking parameters */
4033 memset(&f, 0, sizeof(f));
4034 f.l_type = lockType;
4035 f.l_whence = SEEK_SET;
4036 f.l_start = ofst;
4037 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004038
drh3cb93392011-03-12 18:10:44 +00004039 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4040 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4041 }
drhd9e5c4f2010-05-12 18:01:39 +00004042
4043 /* Update the global lock state and do debug tracing */
4044#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004045 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004046 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00004047 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004048 if( rc==SQLITE_OK ){
4049 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004050 OSTRACE(("unlock %d ok", ofst));
4051 pShmNode->exclMask &= ~mask;
4052 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004053 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004054 OSTRACE(("read-lock %d ok", ofst));
4055 pShmNode->exclMask &= ~mask;
4056 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004057 }else{
4058 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004059 OSTRACE(("write-lock %d ok", ofst));
4060 pShmNode->exclMask |= mask;
4061 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004062 }
4063 }else{
4064 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004065 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004066 }else if( lockType==F_RDLCK ){
4067 OSTRACE(("read-lock failed"));
4068 }else{
4069 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004070 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004071 }
4072 }
drh20e1f082010-05-31 16:10:12 +00004073 OSTRACE((" - afterwards %03x,%03x\n",
4074 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004075 }
drhd9e5c4f2010-05-12 18:01:39 +00004076#endif
4077
4078 return rc;
4079}
4080
drhd9e5c4f2010-05-12 18:01:39 +00004081
4082/*
drhd91c68f2010-05-14 14:52:25 +00004083** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004084**
4085** This is not a VFS shared-memory method; it is a utility function called
4086** by VFS shared-memory methods.
4087*/
drhd91c68f2010-05-14 14:52:25 +00004088static void unixShmPurge(unixFile *pFd){
4089 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004090 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004091 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004092 int i;
drhd91c68f2010-05-14 14:52:25 +00004093 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004094 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004095 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004096 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004097 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004098 }else{
4099 sqlite3_free(p->apRegion[i]);
4100 }
dan13a3cb82010-06-11 19:04:21 +00004101 }
dan18801912010-06-14 14:07:50 +00004102 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004103 if( p->h>=0 ){
4104 robust_close(pFd, p->h, __LINE__);
4105 p->h = -1;
4106 }
drhd91c68f2010-05-14 14:52:25 +00004107 p->pInode->pShmNode = 0;
4108 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004109 }
4110}
4111
4112/*
danda9fe0c2010-07-13 18:44:03 +00004113** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004114** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004115**
drh7234c6d2010-06-19 15:10:09 +00004116** The file used to implement shared-memory is in the same directory
4117** as the open database file and has the same name as the open database
4118** file with the "-shm" suffix added. For example, if the database file
4119** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004120** for shared memory will be called "/home/user1/config.db-shm".
4121**
4122** Another approach to is to use files in /dev/shm or /dev/tmp or an
4123** some other tmpfs mount. But if a file in a different directory
4124** from the database file is used, then differing access permissions
4125** or a chroot() might cause two different processes on the same
4126** database to end up using different files for shared memory -
4127** meaning that their memory would not really be shared - resulting
4128** in database corruption. Nevertheless, this tmpfs file usage
4129** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4130** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4131** option results in an incompatible build of SQLite; builds of SQLite
4132** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4133** same database file at the same time, database corruption will likely
4134** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4135** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004136**
4137** When opening a new shared-memory file, if no other instances of that
4138** file are currently open, in this process or in other processes, then
4139** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004140**
4141** If the original database file (pDbFd) is using the "unix-excl" VFS
4142** that means that an exclusive lock is held on the database file and
4143** that no other processes are able to read or write the database. In
4144** that case, we do not really need shared memory. No shared memory
4145** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004146*/
danda9fe0c2010-07-13 18:44:03 +00004147static int unixOpenSharedMemory(unixFile *pDbFd){
4148 struct unixShm *p = 0; /* The connection to be opened */
4149 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4150 int rc; /* Result code */
4151 unixInodeInfo *pInode; /* The inode of fd */
4152 char *zShmFilename; /* Name of the file used for SHM */
4153 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004154
danda9fe0c2010-07-13 18:44:03 +00004155 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004156 p = sqlite3_malloc( sizeof(*p) );
4157 if( p==0 ) return SQLITE_NOMEM;
4158 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004159 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004160
danda9fe0c2010-07-13 18:44:03 +00004161 /* Check to see if a unixShmNode object already exists. Reuse an existing
4162 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004163 */
4164 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004165 pInode = pDbFd->pInode;
4166 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004167 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004168 struct stat sStat; /* fstat() info for database file */
4169
4170 /* Call fstat() to figure out the permissions on the database file. If
4171 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004172 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004173 */
drh3cb93392011-03-12 18:10:44 +00004174 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004175 rc = SQLITE_IOERR_FSTAT;
4176 goto shm_open_err;
4177 }
4178
drha4ced192010-07-15 18:32:40 +00004179#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004180 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004181#else
drh52bcde02012-01-03 14:50:45 +00004182 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004183#endif
drh7234c6d2010-06-19 15:10:09 +00004184 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004185 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004186 rc = SQLITE_NOMEM;
4187 goto shm_open_err;
4188 }
drh9cb5a0d2012-01-05 21:19:54 +00004189 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004190 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004191#ifdef SQLITE_SHM_DIRECTORY
4192 sqlite3_snprintf(nShmFilename, zShmFilename,
4193 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4194 (u32)sStat.st_ino, (u32)sStat.st_dev);
4195#else
drh7234c6d2010-06-19 15:10:09 +00004196 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004197 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004198#endif
drhd91c68f2010-05-14 14:52:25 +00004199 pShmNode->h = -1;
4200 pDbFd->pInode->pShmNode = pShmNode;
4201 pShmNode->pInode = pDbFd->pInode;
4202 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4203 if( pShmNode->mutex==0 ){
4204 rc = SQLITE_NOMEM;
4205 goto shm_open_err;
4206 }
drhd9e5c4f2010-05-12 18:01:39 +00004207
drh3cb93392011-03-12 18:10:44 +00004208 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004209 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004210 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004211 openFlags = O_RDONLY;
4212 pShmNode->isReadonly = 1;
4213 }
4214 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004215 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004216 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4217 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004218 }
drhac7c3ac2012-02-11 19:23:48 +00004219
4220 /* If this process is running as root, make sure that the SHM file
4221 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004222 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004223 */
drhed466822012-05-31 13:10:49 +00004224 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004225
4226 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004227 ** If not, truncate the file to zero length.
4228 */
4229 rc = SQLITE_OK;
4230 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4231 if( robust_ftruncate(pShmNode->h, 0) ){
4232 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004233 }
4234 }
drh66dfec8b2011-06-01 20:01:49 +00004235 if( rc==SQLITE_OK ){
4236 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4237 }
4238 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004239 }
drhd9e5c4f2010-05-12 18:01:39 +00004240 }
4241
drhd91c68f2010-05-14 14:52:25 +00004242 /* Make the new connection a child of the unixShmNode */
4243 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004244#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004245 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004246#endif
drhd91c68f2010-05-14 14:52:25 +00004247 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004248 pDbFd->pShm = p;
4249 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004250
4251 /* The reference count on pShmNode has already been incremented under
4252 ** the cover of the unixEnterMutex() mutex and the pointer from the
4253 ** new (struct unixShm) object to the pShmNode has been set. All that is
4254 ** left to do is to link the new object into the linked list starting
4255 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4256 ** mutex.
4257 */
4258 sqlite3_mutex_enter(pShmNode->mutex);
4259 p->pNext = pShmNode->pFirst;
4260 pShmNode->pFirst = p;
4261 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004262 return SQLITE_OK;
4263
4264 /* Jump here on any error */
4265shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004266 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004267 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004268 unixLeaveMutex();
4269 return rc;
4270}
4271
4272/*
danda9fe0c2010-07-13 18:44:03 +00004273** This function is called to obtain a pointer to region iRegion of the
4274** shared-memory associated with the database file fd. Shared-memory regions
4275** are numbered starting from zero. Each shared-memory region is szRegion
4276** bytes in size.
4277**
4278** If an error occurs, an error code is returned and *pp is set to NULL.
4279**
4280** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4281** region has not been allocated (by any client, including one running in a
4282** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4283** bExtend is non-zero and the requested shared-memory region has not yet
4284** been allocated, it is allocated by this function.
4285**
4286** If the shared-memory region has already been allocated or is allocated by
4287** this call as described above, then it is mapped into this processes
4288** address space (if it is not already), *pp is set to point to the mapped
4289** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004290*/
danda9fe0c2010-07-13 18:44:03 +00004291static int unixShmMap(
4292 sqlite3_file *fd, /* Handle open on database file */
4293 int iRegion, /* Region to retrieve */
4294 int szRegion, /* Size of regions */
4295 int bExtend, /* True to extend file if necessary */
4296 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004297){
danda9fe0c2010-07-13 18:44:03 +00004298 unixFile *pDbFd = (unixFile*)fd;
4299 unixShm *p;
4300 unixShmNode *pShmNode;
4301 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004302
danda9fe0c2010-07-13 18:44:03 +00004303 /* If the shared-memory file has not yet been opened, open it now. */
4304 if( pDbFd->pShm==0 ){
4305 rc = unixOpenSharedMemory(pDbFd);
4306 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004307 }
drhd9e5c4f2010-05-12 18:01:39 +00004308
danda9fe0c2010-07-13 18:44:03 +00004309 p = pDbFd->pShm;
4310 pShmNode = p->pShmNode;
4311 sqlite3_mutex_enter(pShmNode->mutex);
4312 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004313 assert( pShmNode->pInode==pDbFd->pInode );
4314 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4315 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004316
4317 if( pShmNode->nRegion<=iRegion ){
4318 char **apNew; /* New apRegion[] array */
4319 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4320 struct stat sStat; /* Used by fstat() */
4321
4322 pShmNode->szRegion = szRegion;
4323
drh3cb93392011-03-12 18:10:44 +00004324 if( pShmNode->h>=0 ){
4325 /* The requested region is not mapped into this processes address space.
4326 ** Check to see if it has been allocated (i.e. if the wal-index file is
4327 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004328 */
drh3cb93392011-03-12 18:10:44 +00004329 if( osFstat(pShmNode->h, &sStat) ){
4330 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004331 goto shmpage_out;
4332 }
drh3cb93392011-03-12 18:10:44 +00004333
4334 if( sStat.st_size<nByte ){
4335 /* The requested memory region does not exist. If bExtend is set to
4336 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004337 */
dan47a2b4a2013-04-26 16:09:29 +00004338 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004339 goto shmpage_out;
4340 }
dan47a2b4a2013-04-26 16:09:29 +00004341
4342 /* Alternatively, if bExtend is true, extend the file. Do this by
4343 ** writing a single byte to the end of each (OS) page being
4344 ** allocated or extended. Technically, we need only write to the
4345 ** last page in order to extend the file. But writing to all new
4346 ** pages forces the OS to allocate them immediately, which reduces
4347 ** the chances of SIGBUS while accessing the mapped region later on.
4348 */
4349 else{
4350 static const int pgsz = 4096;
4351 int iPg;
4352
4353 /* Write to the last byte of each newly allocated or extended page */
4354 assert( (nByte % pgsz)==0 );
4355 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4356 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4357 const char *zFile = pShmNode->zFilename;
4358 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4359 goto shmpage_out;
4360 }
4361 }
drh3cb93392011-03-12 18:10:44 +00004362 }
4363 }
danda9fe0c2010-07-13 18:44:03 +00004364 }
4365
4366 /* Map the requested memory region into this processes address space. */
4367 apNew = (char **)sqlite3_realloc(
4368 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4369 );
4370 if( !apNew ){
4371 rc = SQLITE_IOERR_NOMEM;
4372 goto shmpage_out;
4373 }
4374 pShmNode->apRegion = apNew;
4375 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004376 void *pMem;
4377 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004378 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004379 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004380 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004381 );
4382 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004383 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004384 goto shmpage_out;
4385 }
4386 }else{
4387 pMem = sqlite3_malloc(szRegion);
4388 if( pMem==0 ){
4389 rc = SQLITE_NOMEM;
4390 goto shmpage_out;
4391 }
4392 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004393 }
4394 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4395 pShmNode->nRegion++;
4396 }
4397 }
4398
4399shmpage_out:
4400 if( pShmNode->nRegion>iRegion ){
4401 *pp = pShmNode->apRegion[iRegion];
4402 }else{
4403 *pp = 0;
4404 }
drh66dfec8b2011-06-01 20:01:49 +00004405 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004406 sqlite3_mutex_leave(pShmNode->mutex);
4407 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004408}
4409
4410/*
drhd9e5c4f2010-05-12 18:01:39 +00004411** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004412**
4413** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4414** different here than in posix. In xShmLock(), one can go from unlocked
4415** to shared and back or from unlocked to exclusive and back. But one may
4416** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004417*/
4418static int unixShmLock(
4419 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004420 int ofst, /* First lock to acquire or release */
4421 int n, /* Number of locks to acquire or release */
4422 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004423){
drh73b64e42010-05-30 19:55:15 +00004424 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4425 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4426 unixShm *pX; /* For looping over all siblings */
4427 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4428 int rc = SQLITE_OK; /* Result code */
4429 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004430
drhd91c68f2010-05-14 14:52:25 +00004431 assert( pShmNode==pDbFd->pInode->pShmNode );
4432 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004433 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004434 assert( n>=1 );
4435 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4436 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4437 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4438 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4439 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004440 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4441 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004442
drhc99597c2010-05-31 01:41:15 +00004443 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004444 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004445 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004446 if( flags & SQLITE_SHM_UNLOCK ){
4447 u16 allMask = 0; /* Mask of locks held by siblings */
4448
4449 /* See if any siblings hold this same lock */
4450 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4451 if( pX==p ) continue;
4452 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4453 allMask |= pX->sharedMask;
4454 }
4455
4456 /* Unlock the system-level locks */
4457 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004458 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004459 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004460 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004461 }
drh73b64e42010-05-30 19:55:15 +00004462
4463 /* Undo the local locks */
4464 if( rc==SQLITE_OK ){
4465 p->exclMask &= ~mask;
4466 p->sharedMask &= ~mask;
4467 }
4468 }else if( flags & SQLITE_SHM_SHARED ){
4469 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4470
4471 /* Find out which shared locks are already held by sibling connections.
4472 ** If any sibling already holds an exclusive lock, go ahead and return
4473 ** SQLITE_BUSY.
4474 */
4475 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004476 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004477 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004478 break;
4479 }
4480 allShared |= pX->sharedMask;
4481 }
4482
4483 /* Get shared locks at the system level, if necessary */
4484 if( rc==SQLITE_OK ){
4485 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004486 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004487 }else{
drh73b64e42010-05-30 19:55:15 +00004488 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004489 }
drhd9e5c4f2010-05-12 18:01:39 +00004490 }
drh73b64e42010-05-30 19:55:15 +00004491
4492 /* Get the local shared locks */
4493 if( rc==SQLITE_OK ){
4494 p->sharedMask |= mask;
4495 }
4496 }else{
4497 /* Make sure no sibling connections hold locks that will block this
4498 ** lock. If any do, return SQLITE_BUSY right away.
4499 */
4500 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004501 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4502 rc = SQLITE_BUSY;
4503 break;
4504 }
4505 }
4506
4507 /* Get the exclusive locks at the system level. Then if successful
4508 ** also mark the local connection as being locked.
4509 */
4510 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004511 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004512 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004513 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004514 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004515 }
drhd9e5c4f2010-05-12 18:01:39 +00004516 }
4517 }
drhd91c68f2010-05-14 14:52:25 +00004518 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004519 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4520 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004521 return rc;
4522}
4523
drh286a2882010-05-20 23:51:06 +00004524/*
4525** Implement a memory barrier or memory fence on shared memory.
4526**
4527** All loads and stores begun before the barrier must complete before
4528** any load or store begun after the barrier.
4529*/
4530static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004531 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004532){
drhff828942010-06-26 21:34:06 +00004533 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004534 unixEnterMutex();
4535 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004536}
4537
dan18801912010-06-14 14:07:50 +00004538/*
danda9fe0c2010-07-13 18:44:03 +00004539** Close a connection to shared-memory. Delete the underlying
4540** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004541**
4542** If there is no shared memory associated with the connection then this
4543** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004544*/
danda9fe0c2010-07-13 18:44:03 +00004545static int unixShmUnmap(
4546 sqlite3_file *fd, /* The underlying database file */
4547 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004548){
danda9fe0c2010-07-13 18:44:03 +00004549 unixShm *p; /* The connection to be closed */
4550 unixShmNode *pShmNode; /* The underlying shared-memory file */
4551 unixShm **pp; /* For looping over sibling connections */
4552 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004553
danda9fe0c2010-07-13 18:44:03 +00004554 pDbFd = (unixFile*)fd;
4555 p = pDbFd->pShm;
4556 if( p==0 ) return SQLITE_OK;
4557 pShmNode = p->pShmNode;
4558
4559 assert( pShmNode==pDbFd->pInode->pShmNode );
4560 assert( pShmNode->pInode==pDbFd->pInode );
4561
4562 /* Remove connection p from the set of connections associated
4563 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004564 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004565 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4566 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004567
danda9fe0c2010-07-13 18:44:03 +00004568 /* Free the connection p */
4569 sqlite3_free(p);
4570 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004571 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004572
4573 /* If pShmNode->nRef has reached 0, then close the underlying
4574 ** shared-memory file, too */
4575 unixEnterMutex();
4576 assert( pShmNode->nRef>0 );
4577 pShmNode->nRef--;
4578 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004579 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004580 unixShmPurge(pDbFd);
4581 }
4582 unixLeaveMutex();
4583
4584 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004585}
drh286a2882010-05-20 23:51:06 +00004586
danda9fe0c2010-07-13 18:44:03 +00004587
drhd9e5c4f2010-05-12 18:01:39 +00004588#else
drh6b017cc2010-06-14 18:01:46 +00004589# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004590# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004591# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004592# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004593#endif /* #ifndef SQLITE_OMIT_WAL */
4594
drh734c9862008-11-28 15:37:20 +00004595/*
danaef49d72013-03-25 16:28:54 +00004596** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004597*/
danf23da962013-03-23 21:00:41 +00004598static void unixUnmapfile(unixFile *pFd){
4599 assert( pFd->nFetchOut==0 );
drh9b4c59f2013-04-15 17:03:42 +00004600#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004601 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004602 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004603 pFd->pMapRegion = 0;
4604 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004605 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004606 }
drh6e0b6d52013-04-09 16:19:20 +00004607#endif
danf23da962013-03-23 21:00:41 +00004608}
dan5d8a1372013-03-19 19:28:06 +00004609
drh9b4c59f2013-04-15 17:03:42 +00004610#if SQLITE_MAX_MMAP_SIZE>0
danaef49d72013-03-25 16:28:54 +00004611/*
dane6ecd662013-04-01 17:56:59 +00004612** Return the system page size.
4613*/
4614static int unixGetPagesize(void){
4615#if HAVE_MREMAP
4616 return 512;
drh85830a72013-04-03 00:42:01 +00004617#elif defined(_BSD_SOURCE)
dane6ecd662013-04-01 17:56:59 +00004618 return getpagesize();
4619#else
4620 return (int)sysconf(_SC_PAGESIZE);
4621#endif
4622}
drh9b4c59f2013-04-15 17:03:42 +00004623#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dane6ecd662013-04-01 17:56:59 +00004624
drh9b4c59f2013-04-15 17:03:42 +00004625#if SQLITE_MAX_MMAP_SIZE>0
dane6ecd662013-04-01 17:56:59 +00004626/*
4627** Attempt to set the size of the memory mapping maintained by file
4628** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4629**
4630** If successful, this function sets the following variables:
4631**
4632** unixFile.pMapRegion
4633** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004634** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004635**
4636** If unsuccessful, an error message is logged via sqlite3_log() and
4637** the three variables above are zeroed. In this case SQLite should
4638** continue accessing the database using the xRead() and xWrite()
4639** methods.
4640*/
4641static void unixRemapfile(
4642 unixFile *pFd, /* File descriptor object */
4643 i64 nNew /* Required mapping size */
4644){
dan4ff7bc42013-04-02 12:04:09 +00004645 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004646 int h = pFd->h; /* File descriptor open on db file */
4647 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004648 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004649 u8 *pNew = 0; /* Location of new mapping */
4650 int flags = PROT_READ; /* Flags to pass to mmap() */
4651
4652 assert( pFd->nFetchOut==0 );
4653 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004654 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004655 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004656 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004657 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004658
4659 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4660
4661 if( pOrig ){
4662 const int szSyspage = unixGetPagesize();
4663 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4664 u8 *pReq = &pOrig[nReuse];
4665
4666 /* Unmap any pages of the existing mapping that cannot be reused. */
4667 if( nReuse!=nOrig ){
4668 osMunmap(pReq, nOrig-nReuse);
4669 }
4670
4671#if HAVE_MREMAP
4672 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004673 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004674#else
4675 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4676 if( pNew!=MAP_FAILED ){
4677 if( pNew!=pReq ){
4678 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004679 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004680 }else{
4681 pNew = pOrig;
4682 }
4683 }
4684#endif
4685
dan48ccef82013-04-02 20:55:01 +00004686 /* The attempt to extend the existing mapping failed. Free it. */
4687 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004688 osMunmap(pOrig, nReuse);
4689 }
4690 }
4691
4692 /* If pNew is still NULL, try to create an entirely new mapping. */
4693 if( pNew==0 ){
4694 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004695 }
4696
dan4ff7bc42013-04-02 12:04:09 +00004697 if( pNew==MAP_FAILED ){
4698 pNew = 0;
4699 nNew = 0;
4700 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4701
4702 /* If the mmap() above failed, assume that all subsequent mmap() calls
4703 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4704 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004705 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004706 }
dane6ecd662013-04-01 17:56:59 +00004707 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004708 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004709}
drh6e0b6d52013-04-09 16:19:20 +00004710#endif
dane6ecd662013-04-01 17:56:59 +00004711
4712/*
danaef49d72013-03-25 16:28:54 +00004713** Memory map or remap the file opened by file-descriptor pFd (if the file
4714** is already mapped, the existing mapping is replaced by the new). Or, if
4715** there already exists a mapping for this file, and there are still
4716** outstanding xFetch() references to it, this function is a no-op.
4717**
4718** If parameter nByte is non-negative, then it is the requested size of
4719** the mapping to create. Otherwise, if nByte is less than zero, then the
4720** requested size is the size of the file on disk. The actual size of the
4721** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004722** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004723**
4724** SQLITE_OK is returned if no error occurs (even if the mapping is not
4725** recreated as a result of outstanding references) or an SQLite error
4726** code otherwise.
4727*/
danf23da962013-03-23 21:00:41 +00004728static int unixMapfile(unixFile *pFd, i64 nByte){
drh9b4c59f2013-04-15 17:03:42 +00004729#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004730 i64 nMap = nByte;
4731 int rc;
daneb97b292013-03-20 14:26:59 +00004732
danf23da962013-03-23 21:00:41 +00004733 assert( nMap>=0 || pFd->nFetchOut==0 );
4734 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4735
4736 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004737 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004738 rc = osFstat(pFd->h, &statbuf);
4739 if( rc!=SQLITE_OK ){
4740 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004741 }
danf23da962013-03-23 21:00:41 +00004742 nMap = statbuf.st_size;
4743 }
drh9b4c59f2013-04-15 17:03:42 +00004744 if( nMap>pFd->mmapSizeMax ){
4745 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004746 }
4747
danf23da962013-03-23 21:00:41 +00004748 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004749 if( nMap>0 ){
4750 unixRemapfile(pFd, nMap);
4751 }else{
danb7e3a322013-03-25 20:30:13 +00004752 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004753 }
4754 }
drh6e0b6d52013-04-09 16:19:20 +00004755#endif
dan5d8a1372013-03-19 19:28:06 +00004756
danf23da962013-03-23 21:00:41 +00004757 return SQLITE_OK;
4758}
4759
danaef49d72013-03-25 16:28:54 +00004760/*
4761** If possible, return a pointer to a mapping of file fd starting at offset
4762** iOff. The mapping must be valid for at least nAmt bytes.
4763**
4764** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4765** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4766** Finally, if an error does occur, return an SQLite error code. The final
4767** value of *pp is undefined in this case.
4768**
4769** If this function does return a pointer, the caller must eventually
4770** release the reference by calling unixUnfetch().
4771*/
danf23da962013-03-23 21:00:41 +00004772static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004773#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004774 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004775#endif
danf23da962013-03-23 21:00:41 +00004776 *pp = 0;
4777
drh9b4c59f2013-04-15 17:03:42 +00004778#if SQLITE_MAX_MMAP_SIZE>0
4779 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004780 if( pFd->pMapRegion==0 ){
4781 int rc = unixMapfile(pFd, -1);
4782 if( rc!=SQLITE_OK ) return rc;
4783 }
4784 if( pFd->mmapSize >= iOff+nAmt ){
4785 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4786 pFd->nFetchOut++;
4787 }
4788 }
drh6e0b6d52013-04-09 16:19:20 +00004789#endif
danf23da962013-03-23 21:00:41 +00004790 return SQLITE_OK;
4791}
4792
danaef49d72013-03-25 16:28:54 +00004793/*
dandf737fe2013-03-25 17:00:24 +00004794** If the third argument is non-NULL, then this function releases a
4795** reference obtained by an earlier call to unixFetch(). The second
4796** argument passed to this function must be the same as the corresponding
4797** argument that was passed to the unixFetch() invocation.
4798**
4799** Or, if the third argument is NULL, then this function is being called
4800** to inform the VFS layer that, according to POSIX, any existing mapping
4801** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004802*/
dandf737fe2013-03-25 17:00:24 +00004803static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
danf23da962013-03-23 21:00:41 +00004804 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhda8caa02013-04-22 23:38:50 +00004805 UNUSED_PARAMETER(iOff);
danf23da962013-03-23 21:00:41 +00004806
danaef49d72013-03-25 16:28:54 +00004807 /* If p==0 (unmap the entire file) then there must be no outstanding
4808 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4809 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004810 assert( (p==0)==(pFd->nFetchOut==0) );
4811
dandf737fe2013-03-25 17:00:24 +00004812 /* If p!=0, it must match the iOff value. */
4813 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4814
danf23da962013-03-23 21:00:41 +00004815 if( p ){
4816 pFd->nFetchOut--;
4817 }else{
4818 unixUnmapfile(pFd);
4819 }
4820
4821 assert( pFd->nFetchOut>=0 );
4822 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004823}
4824
4825/*
drh734c9862008-11-28 15:37:20 +00004826** Here ends the implementation of all sqlite3_file methods.
4827**
4828********************** End sqlite3_file Methods *******************************
4829******************************************************************************/
4830
4831/*
drh6b9d6dd2008-12-03 19:34:47 +00004832** This division contains definitions of sqlite3_io_methods objects that
4833** implement various file locking strategies. It also contains definitions
4834** of "finder" functions. A finder-function is used to locate the appropriate
4835** sqlite3_io_methods object for a particular database file. The pAppData
4836** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4837** the correct finder-function for that VFS.
4838**
4839** Most finder functions return a pointer to a fixed sqlite3_io_methods
4840** object. The only interesting finder-function is autolockIoFinder, which
4841** looks at the filesystem type and tries to guess the best locking
4842** strategy from that.
4843**
drh1875f7a2008-12-08 18:19:17 +00004844** For finder-funtion F, two objects are created:
4845**
4846** (1) The real finder-function named "FImpt()".
4847**
dane946c392009-08-22 11:39:46 +00004848** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004849**
4850**
4851** A pointer to the F pointer is used as the pAppData value for VFS
4852** objects. We have to do this instead of letting pAppData point
4853** directly at the finder-function since C90 rules prevent a void*
4854** from be cast into a function pointer.
4855**
drh6b9d6dd2008-12-03 19:34:47 +00004856**
drh7708e972008-11-29 00:56:52 +00004857** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004858**
drh7708e972008-11-29 00:56:52 +00004859** * A constant sqlite3_io_methods object call METHOD that has locking
4860** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4861**
4862** * An I/O method finder function called FINDER that returns a pointer
4863** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004864*/
drhd9e5c4f2010-05-12 18:01:39 +00004865#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004866static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004867 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004868 CLOSE, /* xClose */ \
4869 unixRead, /* xRead */ \
4870 unixWrite, /* xWrite */ \
4871 unixTruncate, /* xTruncate */ \
4872 unixSync, /* xSync */ \
4873 unixFileSize, /* xFileSize */ \
4874 LOCK, /* xLock */ \
4875 UNLOCK, /* xUnlock */ \
4876 CKLOCK, /* xCheckReservedLock */ \
4877 unixFileControl, /* xFileControl */ \
4878 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004879 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004880 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004881 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004882 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004883 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004884 unixFetch, /* xFetch */ \
4885 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004886}; \
drh0c2694b2009-09-03 16:23:44 +00004887static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4888 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004889 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004890} \
drh0c2694b2009-09-03 16:23:44 +00004891static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004892 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004893
4894/*
4895** Here are all of the sqlite3_io_methods objects for each of the
4896** locking strategies. Functions that return pointers to these methods
4897** are also created.
4898*/
4899IOMETHODS(
4900 posixIoFinder, /* Finder function name */
4901 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004902 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004903 unixClose, /* xClose method */
4904 unixLock, /* xLock method */
4905 unixUnlock, /* xUnlock method */
4906 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004907)
drh7708e972008-11-29 00:56:52 +00004908IOMETHODS(
4909 nolockIoFinder, /* Finder function name */
4910 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004911 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004912 nolockClose, /* xClose method */
4913 nolockLock, /* xLock method */
4914 nolockUnlock, /* xUnlock method */
4915 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004916)
drh7708e972008-11-29 00:56:52 +00004917IOMETHODS(
4918 dotlockIoFinder, /* Finder function name */
4919 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004920 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004921 dotlockClose, /* xClose method */
4922 dotlockLock, /* xLock method */
4923 dotlockUnlock, /* xUnlock method */
4924 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004925)
drh7708e972008-11-29 00:56:52 +00004926
chw78a13182009-04-07 05:35:03 +00004927#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004928IOMETHODS(
4929 flockIoFinder, /* Finder function name */
4930 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004931 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004932 flockClose, /* xClose method */
4933 flockLock, /* xLock method */
4934 flockUnlock, /* xUnlock method */
4935 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004936)
drh7708e972008-11-29 00:56:52 +00004937#endif
4938
drh6c7d5c52008-11-21 20:32:33 +00004939#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004940IOMETHODS(
4941 semIoFinder, /* Finder function name */
4942 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004943 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004944 semClose, /* xClose method */
4945 semLock, /* xLock method */
4946 semUnlock, /* xUnlock method */
4947 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004948)
aswiftaebf4132008-11-21 00:10:35 +00004949#endif
drh7708e972008-11-29 00:56:52 +00004950
drhd2cb50b2009-01-09 21:41:17 +00004951#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004952IOMETHODS(
4953 afpIoFinder, /* Finder function name */
4954 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004955 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004956 afpClose, /* xClose method */
4957 afpLock, /* xLock method */
4958 afpUnlock, /* xUnlock method */
4959 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004960)
drh715ff302008-12-03 22:32:44 +00004961#endif
4962
4963/*
4964** The proxy locking method is a "super-method" in the sense that it
4965** opens secondary file descriptors for the conch and lock files and
4966** it uses proxy, dot-file, AFP, and flock() locking methods on those
4967** secondary files. For this reason, the division that implements
4968** proxy locking is located much further down in the file. But we need
4969** to go ahead and define the sqlite3_io_methods and finder function
4970** for proxy locking here. So we forward declare the I/O methods.
4971*/
drhd2cb50b2009-01-09 21:41:17 +00004972#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004973static int proxyClose(sqlite3_file*);
4974static int proxyLock(sqlite3_file*, int);
4975static int proxyUnlock(sqlite3_file*, int);
4976static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004977IOMETHODS(
4978 proxyIoFinder, /* Finder function name */
4979 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004980 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004981 proxyClose, /* xClose method */
4982 proxyLock, /* xLock method */
4983 proxyUnlock, /* xUnlock method */
4984 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004985)
aswiftaebf4132008-11-21 00:10:35 +00004986#endif
drh7708e972008-11-29 00:56:52 +00004987
drh7ed97b92010-01-20 13:07:21 +00004988/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4989#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4990IOMETHODS(
4991 nfsIoFinder, /* Finder function name */
4992 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004993 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004994 unixClose, /* xClose method */
4995 unixLock, /* xLock method */
4996 nfsUnlock, /* xUnlock method */
4997 unixCheckReservedLock /* xCheckReservedLock method */
4998)
4999#endif
drh7708e972008-11-29 00:56:52 +00005000
drhd2cb50b2009-01-09 21:41:17 +00005001#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005002/*
drh6b9d6dd2008-12-03 19:34:47 +00005003** This "finder" function attempts to determine the best locking strategy
5004** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005005** object that implements that strategy.
5006**
5007** This is for MacOSX only.
5008*/
drh1875f7a2008-12-08 18:19:17 +00005009static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005010 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005011 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005012){
5013 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005014 const char *zFilesystem; /* Filesystem type name */
5015 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005016 } aMap[] = {
5017 { "hfs", &posixIoMethods },
5018 { "ufs", &posixIoMethods },
5019 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005020 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005021 { "webdav", &nolockIoMethods },
5022 { 0, 0 }
5023 };
5024 int i;
5025 struct statfs fsInfo;
5026 struct flock lockInfo;
5027
5028 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005029 /* If filePath==NULL that means we are dealing with a transient file
5030 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005031 return &nolockIoMethods;
5032 }
5033 if( statfs(filePath, &fsInfo) != -1 ){
5034 if( fsInfo.f_flags & MNT_RDONLY ){
5035 return &nolockIoMethods;
5036 }
5037 for(i=0; aMap[i].zFilesystem; i++){
5038 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5039 return aMap[i].pMethods;
5040 }
5041 }
5042 }
5043
5044 /* Default case. Handles, amongst others, "nfs".
5045 ** Test byte-range lock using fcntl(). If the call succeeds,
5046 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005047 */
drh7708e972008-11-29 00:56:52 +00005048 lockInfo.l_len = 1;
5049 lockInfo.l_start = 0;
5050 lockInfo.l_whence = SEEK_SET;
5051 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005052 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005053 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5054 return &nfsIoMethods;
5055 } else {
5056 return &posixIoMethods;
5057 }
drh7708e972008-11-29 00:56:52 +00005058 }else{
5059 return &dotlockIoMethods;
5060 }
5061}
drh0c2694b2009-09-03 16:23:44 +00005062static const sqlite3_io_methods
5063 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005064
drhd2cb50b2009-01-09 21:41:17 +00005065#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005066
chw78a13182009-04-07 05:35:03 +00005067#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5068/*
5069** This "finder" function attempts to determine the best locking strategy
5070** for the database file "filePath". It then returns the sqlite3_io_methods
5071** object that implements that strategy.
5072**
5073** This is for VXWorks only.
5074*/
5075static const sqlite3_io_methods *autolockIoFinderImpl(
5076 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005077 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005078){
5079 struct flock lockInfo;
5080
5081 if( !filePath ){
5082 /* If filePath==NULL that means we are dealing with a transient file
5083 ** that does not need to be locked. */
5084 return &nolockIoMethods;
5085 }
5086
5087 /* Test if fcntl() is supported and use POSIX style locks.
5088 ** Otherwise fall back to the named semaphore method.
5089 */
5090 lockInfo.l_len = 1;
5091 lockInfo.l_start = 0;
5092 lockInfo.l_whence = SEEK_SET;
5093 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005094 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005095 return &posixIoMethods;
5096 }else{
5097 return &semIoMethods;
5098 }
5099}
drh0c2694b2009-09-03 16:23:44 +00005100static const sqlite3_io_methods
5101 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005102
5103#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5104
drh7708e972008-11-29 00:56:52 +00005105/*
5106** An abstract type for a pointer to a IO method finder function:
5107*/
drh0c2694b2009-09-03 16:23:44 +00005108typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005109
aswiftaebf4132008-11-21 00:10:35 +00005110
drh734c9862008-11-28 15:37:20 +00005111/****************************************************************************
5112**************************** sqlite3_vfs methods ****************************
5113**
5114** This division contains the implementation of methods on the
5115** sqlite3_vfs object.
5116*/
5117
danielk1977a3d4c882007-03-23 10:08:38 +00005118/*
danielk1977e339d652008-06-28 11:23:00 +00005119** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005120*/
5121static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005122 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005123 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005124 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005125 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005126 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005127){
drh7708e972008-11-29 00:56:52 +00005128 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005129 unixFile *pNew = (unixFile *)pId;
5130 int rc = SQLITE_OK;
5131
drh8af6c222010-05-14 12:43:01 +00005132 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005133
dan00157392010-10-05 11:33:15 +00005134 /* Usually the path zFilename should not be a relative pathname. The
5135 ** exception is when opening the proxy "conch" file in builds that
5136 ** include the special Apple locking styles.
5137 */
dan00157392010-10-05 11:33:15 +00005138#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005139 assert( zFilename==0 || zFilename[0]=='/'
5140 || pVfs->pAppData==(void*)&autolockIoFinder );
5141#else
5142 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005143#endif
dan00157392010-10-05 11:33:15 +00005144
drhb07028f2011-10-14 21:49:18 +00005145 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005146 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005147
drh308c2a52010-05-14 11:30:18 +00005148 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005149 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005150 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005151 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005152 pNew->ctrlFlags = (u8)ctrlFlags;
danede01a92013-05-17 12:10:52 +00005153 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
drhc02a43a2012-01-10 23:18:38 +00005154 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5155 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005156 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005157 }
drh503a6862013-03-01 01:07:17 +00005158 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005159 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005160 }
drh339eb0b2008-03-07 15:34:11 +00005161
drh6c7d5c52008-11-21 20:32:33 +00005162#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005163 pNew->pId = vxworksFindFileId(zFilename);
5164 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005165 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005166 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005167 }
5168#endif
5169
drhc02a43a2012-01-10 23:18:38 +00005170 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005171 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005172 }else{
drh0c2694b2009-09-03 16:23:44 +00005173 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005174#if SQLITE_ENABLE_LOCKING_STYLE
5175 /* Cache zFilename in the locking context (AFP and dotlock override) for
5176 ** proxyLock activation is possible (remote proxy is based on db name)
5177 ** zFilename remains valid until file is closed, to support */
5178 pNew->lockingContext = (void*)zFilename;
5179#endif
drhda0e7682008-07-30 15:27:54 +00005180 }
danielk1977e339d652008-06-28 11:23:00 +00005181
drh7ed97b92010-01-20 13:07:21 +00005182 if( pLockingStyle == &posixIoMethods
5183#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5184 || pLockingStyle == &nfsIoMethods
5185#endif
5186 ){
drh7708e972008-11-29 00:56:52 +00005187 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005188 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005189 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005190 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005191 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005192 ** in two scenarios:
5193 **
5194 ** (a) A call to fstat() failed.
5195 ** (b) A malloc failed.
5196 **
5197 ** Scenario (b) may only occur if the process is holding no other
5198 ** file descriptors open on the same file. If there were other file
5199 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005200 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005201 ** handle h - as it is guaranteed that no posix locks will be released
5202 ** by doing so.
5203 **
5204 ** If scenario (a) caused the error then things are not so safe. The
5205 ** implicit assumption here is that if fstat() fails, things are in
5206 ** such bad shape that dropping a lock or two doesn't matter much.
5207 */
drh0e9365c2011-03-02 02:08:13 +00005208 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005209 h = -1;
5210 }
drh7708e972008-11-29 00:56:52 +00005211 unixLeaveMutex();
5212 }
danielk1977e339d652008-06-28 11:23:00 +00005213
drhd2cb50b2009-01-09 21:41:17 +00005214#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005215 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005216 /* AFP locking uses the file path so it needs to be included in
5217 ** the afpLockingContext.
5218 */
5219 afpLockingContext *pCtx;
5220 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5221 if( pCtx==0 ){
5222 rc = SQLITE_NOMEM;
5223 }else{
5224 /* NB: zFilename exists and remains valid until the file is closed
5225 ** according to requirement F11141. So we do not need to make a
5226 ** copy of the filename. */
5227 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005228 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005229 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005230 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005231 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005232 if( rc!=SQLITE_OK ){
5233 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005234 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005235 h = -1;
5236 }
drh7708e972008-11-29 00:56:52 +00005237 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005238 }
drh7708e972008-11-29 00:56:52 +00005239 }
5240#endif
danielk1977e339d652008-06-28 11:23:00 +00005241
drh7708e972008-11-29 00:56:52 +00005242 else if( pLockingStyle == &dotlockIoMethods ){
5243 /* Dotfile locking uses the file path so it needs to be included in
5244 ** the dotlockLockingContext
5245 */
5246 char *zLockFile;
5247 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005248 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005249 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005250 zLockFile = (char *)sqlite3_malloc(nFilename);
5251 if( zLockFile==0 ){
5252 rc = SQLITE_NOMEM;
5253 }else{
5254 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005255 }
drh7708e972008-11-29 00:56:52 +00005256 pNew->lockingContext = zLockFile;
5257 }
danielk1977e339d652008-06-28 11:23:00 +00005258
drh6c7d5c52008-11-21 20:32:33 +00005259#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005260 else if( pLockingStyle == &semIoMethods ){
5261 /* Named semaphore locking uses the file path so it needs to be
5262 ** included in the semLockingContext
5263 */
5264 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005265 rc = findInodeInfo(pNew, &pNew->pInode);
5266 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5267 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005268 int n;
drh2238dcc2009-08-27 17:56:20 +00005269 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005270 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005271 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005272 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005273 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5274 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005275 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005276 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005277 }
chw97185482008-11-17 08:05:31 +00005278 }
drh7708e972008-11-29 00:56:52 +00005279 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005280 }
drh7708e972008-11-29 00:56:52 +00005281#endif
aswift5b1a2562008-08-22 00:22:35 +00005282
5283 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005284#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005285 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005286 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005287 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005288 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005289 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005290 }
chw97185482008-11-17 08:05:31 +00005291#endif
danielk1977e339d652008-06-28 11:23:00 +00005292 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005293 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005294 }else{
drh7708e972008-11-29 00:56:52 +00005295 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005296 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005297 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005298 }
danielk1977e339d652008-06-28 11:23:00 +00005299 return rc;
drh054889e2005-11-30 03:20:31 +00005300}
drh9c06c952005-11-26 00:25:00 +00005301
danielk1977ad94b582007-08-20 06:44:22 +00005302/*
drh8b3cf822010-06-01 21:02:51 +00005303** Return the name of a directory in which to put temporary files.
5304** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005305*/
drh7234c6d2010-06-19 15:10:09 +00005306static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005307 static const char *azDirs[] = {
5308 0,
aswiftaebf4132008-11-21 00:10:35 +00005309 0,
danielk197717b90b52008-06-06 11:11:25 +00005310 "/var/tmp",
5311 "/usr/tmp",
5312 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005313 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005314 };
drh8b3cf822010-06-01 21:02:51 +00005315 unsigned int i;
5316 struct stat buf;
5317 const char *zDir = 0;
5318
5319 azDirs[0] = sqlite3_temp_directory;
5320 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005321 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005322 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005323 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005324 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005325 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005326 break;
5327 }
5328 return zDir;
5329}
5330
5331/*
5332** Create a temporary file name in zBuf. zBuf must be allocated
5333** by the calling process and must be big enough to hold at least
5334** pVfs->mxPathname bytes.
5335*/
5336static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005337 static const unsigned char zChars[] =
5338 "abcdefghijklmnopqrstuvwxyz"
5339 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5340 "0123456789";
drh41022642008-11-21 00:24:42 +00005341 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005342 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005343
5344 /* It's odd to simulate an io-error here, but really this is just
5345 ** using the io-error infrastructure to test that SQLite handles this
5346 ** function failing.
5347 */
5348 SimulateIOError( return SQLITE_IOERR );
5349
drh7234c6d2010-06-19 15:10:09 +00005350 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005351 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005352
5353 /* Check that the output buffer is large enough for the temporary file
5354 ** name. If it is not, return SQLITE_ERROR.
5355 */
drhc02a43a2012-01-10 23:18:38 +00005356 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005357 return SQLITE_ERROR;
5358 }
5359
5360 do{
drhc02a43a2012-01-10 23:18:38 +00005361 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005362 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005363 sqlite3_randomness(15, &zBuf[j]);
5364 for(i=0; i<15; i++, j++){
5365 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5366 }
5367 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005368 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005369 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005370 return SQLITE_OK;
5371}
5372
drhd2cb50b2009-01-09 21:41:17 +00005373#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005374/*
5375** Routine to transform a unixFile into a proxy-locking unixFile.
5376** Implementation in the proxy-lock division, but used by unixOpen()
5377** if SQLITE_PREFER_PROXY_LOCKING is defined.
5378*/
5379static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005380#endif
drhc66d5b62008-12-03 22:48:32 +00005381
dan08da86a2009-08-21 17:18:03 +00005382/*
5383** Search for an unused file descriptor that was opened on the database
5384** file (not a journal or master-journal file) identified by pathname
5385** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5386** argument to this function.
5387**
5388** Such a file descriptor may exist if a database connection was closed
5389** but the associated file descriptor could not be closed because some
5390** other file descriptor open on the same file is holding a file-lock.
5391** Refer to comments in the unixClose() function and the lengthy comment
5392** describing "Posix Advisory Locking" at the start of this file for
5393** further details. Also, ticket #4018.
5394**
5395** If a suitable file descriptor is found, then it is returned. If no
5396** such file descriptor is located, -1 is returned.
5397*/
dane946c392009-08-22 11:39:46 +00005398static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5399 UnixUnusedFd *pUnused = 0;
5400
5401 /* Do not search for an unused file descriptor on vxworks. Not because
5402 ** vxworks would not benefit from the change (it might, we're not sure),
5403 ** but because no way to test it is currently available. It is better
5404 ** not to risk breaking vxworks support for the sake of such an obscure
5405 ** feature. */
5406#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005407 struct stat sStat; /* Results of stat() call */
5408
5409 /* A stat() call may fail for various reasons. If this happens, it is
5410 ** almost certain that an open() call on the same path will also fail.
5411 ** For this reason, if an error occurs in the stat() call here, it is
5412 ** ignored and -1 is returned. The caller will try to open a new file
5413 ** descriptor on the same path, fail, and return an error to SQLite.
5414 **
5415 ** Even if a subsequent open() call does succeed, the consequences of
5416 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005417 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005418 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005419
5420 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005421 pInode = inodeList;
5422 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5423 || pInode->fileId.ino!=sStat.st_ino) ){
5424 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005425 }
drh8af6c222010-05-14 12:43:01 +00005426 if( pInode ){
dane946c392009-08-22 11:39:46 +00005427 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005428 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005429 pUnused = *pp;
5430 if( pUnused ){
5431 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005432 }
5433 }
5434 unixLeaveMutex();
5435 }
dane946c392009-08-22 11:39:46 +00005436#endif /* if !OS_VXWORKS */
5437 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005438}
danielk197717b90b52008-06-06 11:11:25 +00005439
5440/*
danddb0ac42010-07-14 14:48:58 +00005441** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005442** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005443** and a value suitable for passing as the third argument to open(2) is
5444** written to *pMode. If an IO error occurs, an SQLite error code is
5445** returned and the value of *pMode is not modified.
5446**
drh8c815d12012-02-13 20:16:37 +00005447** In most cases cases, this routine sets *pMode to 0, which will become
5448** an indication to robust_open() to create the file using
5449** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5450** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005451** this function queries the file-system for the permissions on the
5452** corresponding database file and sets *pMode to this value. Whenever
5453** possible, WAL and journal files are created using the same permissions
5454** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005455**
5456** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5457** original filename is unavailable. But 8_3_NAMES is only used for
5458** FAT filesystems and permissions do not matter there, so just use
5459** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005460*/
5461static int findCreateFileMode(
5462 const char *zPath, /* Path of file (possibly) being created */
5463 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005464 mode_t *pMode, /* OUT: Permissions to open file with */
5465 uid_t *pUid, /* OUT: uid to set on the file */
5466 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005467){
5468 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005469 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005470 *pUid = 0;
5471 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005472 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005473 char zDb[MAX_PATHNAME+1]; /* Database file path */
5474 int nDb; /* Number of valid bytes in zDb */
5475 struct stat sStat; /* Output of stat() on database file */
5476
dana0c989d2010-11-05 18:07:37 +00005477 /* zPath is a path to a WAL or journal file. The following block derives
5478 ** the path to the associated database file from zPath. This block handles
5479 ** the following naming conventions:
5480 **
5481 ** "<path to db>-journal"
5482 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005483 ** "<path to db>-journalNN"
5484 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005485 **
drhd337c5b2011-10-20 18:23:35 +00005486 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005487 ** used by the test_multiplex.c module.
5488 */
5489 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005490#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005491 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005492 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005493#else
5494 while( zPath[nDb]!='-' ){
5495 assert( nDb>0 );
5496 assert( zPath[nDb]!='\n' );
5497 nDb--;
5498 }
5499#endif
danddb0ac42010-07-14 14:48:58 +00005500 memcpy(zDb, zPath, nDb);
5501 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005502
drh58384f12011-07-28 00:14:45 +00005503 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005504 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005505 *pUid = sStat.st_uid;
5506 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005507 }else{
5508 rc = SQLITE_IOERR_FSTAT;
5509 }
5510 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5511 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005512 }
5513 return rc;
5514}
5515
5516/*
danielk1977ad94b582007-08-20 06:44:22 +00005517** Open the file zPath.
5518**
danielk1977b4b47412007-08-17 15:53:36 +00005519** Previously, the SQLite OS layer used three functions in place of this
5520** one:
5521**
5522** sqlite3OsOpenReadWrite();
5523** sqlite3OsOpenReadOnly();
5524** sqlite3OsOpenExclusive();
5525**
5526** These calls correspond to the following combinations of flags:
5527**
5528** ReadWrite() -> (READWRITE | CREATE)
5529** ReadOnly() -> (READONLY)
5530** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5531**
5532** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5533** true, the file was configured to be automatically deleted when the
5534** file handle closed. To achieve the same effect using this new
5535** interface, add the DELETEONCLOSE flag to those specified above for
5536** OpenExclusive().
5537*/
5538static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005539 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5540 const char *zPath, /* Pathname of file to be opened */
5541 sqlite3_file *pFile, /* The file descriptor to be filled in */
5542 int flags, /* Input flags to control the opening */
5543 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005544){
dan08da86a2009-08-21 17:18:03 +00005545 unixFile *p = (unixFile *)pFile;
5546 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005547 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005548 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005549 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005550 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005551 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005552
5553 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5554 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5555 int isCreate = (flags & SQLITE_OPEN_CREATE);
5556 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5557 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005558#if SQLITE_ENABLE_LOCKING_STYLE
5559 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5560#endif
drh3d4435b2011-08-26 20:55:50 +00005561#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5562 struct statfs fsInfo;
5563#endif
danielk1977b4b47412007-08-17 15:53:36 +00005564
danielk1977fee2d252007-08-18 10:59:19 +00005565 /* If creating a master or main-file journal, this function will open
5566 ** a file-descriptor on the directory too. The first time unixSync()
5567 ** is called the directory file descriptor will be fsync()ed and close()d.
5568 */
drh0059eae2011-08-08 23:48:40 +00005569 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005570 eType==SQLITE_OPEN_MASTER_JOURNAL
5571 || eType==SQLITE_OPEN_MAIN_JOURNAL
5572 || eType==SQLITE_OPEN_WAL
5573 ));
danielk1977fee2d252007-08-18 10:59:19 +00005574
danielk197717b90b52008-06-06 11:11:25 +00005575 /* If argument zPath is a NULL pointer, this function is required to open
5576 ** a temporary file. Use this buffer to store the file name in.
5577 */
drhc02a43a2012-01-10 23:18:38 +00005578 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005579 const char *zName = zPath;
5580
danielk1977fee2d252007-08-18 10:59:19 +00005581 /* Check the following statements are true:
5582 **
5583 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5584 ** (b) if CREATE is set, then READWRITE must also be set, and
5585 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005586 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005587 */
danielk1977b4b47412007-08-17 15:53:36 +00005588 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005589 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005590 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005591 assert(isDelete==0 || isCreate);
5592
danddb0ac42010-07-14 14:48:58 +00005593 /* The main DB, main journal, WAL file and master journal are never
5594 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005595 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5596 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5597 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005598 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005599
danielk1977fee2d252007-08-18 10:59:19 +00005600 /* Assert that the upper layer has set one of the "file-type" flags. */
5601 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5602 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5603 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005604 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005605 );
5606
dan08da86a2009-08-21 17:18:03 +00005607 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005608
dan08da86a2009-08-21 17:18:03 +00005609 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005610 UnixUnusedFd *pUnused;
5611 pUnused = findReusableFd(zName, flags);
5612 if( pUnused ){
5613 fd = pUnused->fd;
5614 }else{
dan6aa657f2009-08-24 18:57:58 +00005615 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005616 if( !pUnused ){
5617 return SQLITE_NOMEM;
5618 }
5619 }
5620 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005621
5622 /* Database filenames are double-zero terminated if they are not
5623 ** URIs with parameters. Hence, they can always be passed into
5624 ** sqlite3_uri_parameter(). */
5625 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5626
dan08da86a2009-08-21 17:18:03 +00005627 }else if( !zName ){
5628 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005629 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005630 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005631 if( rc!=SQLITE_OK ){
5632 return rc;
5633 }
5634 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005635
5636 /* Generated temporary filenames are always double-zero terminated
5637 ** for use by sqlite3_uri_parameter(). */
5638 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005639 }
5640
dan08da86a2009-08-21 17:18:03 +00005641 /* Determine the value of the flags parameter passed to POSIX function
5642 ** open(). These must be calculated even if open() is not called, as
5643 ** they may be stored as part of the file handle and used by the
5644 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005645 if( isReadonly ) openFlags |= O_RDONLY;
5646 if( isReadWrite ) openFlags |= O_RDWR;
5647 if( isCreate ) openFlags |= O_CREAT;
5648 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5649 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005650
danielk1977b4b47412007-08-17 15:53:36 +00005651 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005652 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005653 uid_t uid; /* Userid for the file */
5654 gid_t gid; /* Groupid for the file */
5655 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005656 if( rc!=SQLITE_OK ){
5657 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005658 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005659 return rc;
5660 }
drhad4f1e52011-03-04 15:43:57 +00005661 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005662 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005663 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5664 /* Failed to open the file for read/write access. Try read-only. */
5665 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005666 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005667 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005668 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005669 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005670 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005671 }
5672 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005673 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005674 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005675 }
drhac7c3ac2012-02-11 19:23:48 +00005676
5677 /* If this process is running as root and if creating a new rollback
5678 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005679 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005680 */
5681 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005682 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005683 }
danielk1977b4b47412007-08-17 15:53:36 +00005684 }
dan08da86a2009-08-21 17:18:03 +00005685 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005686 if( pOutFlags ){
5687 *pOutFlags = flags;
5688 }
5689
dane946c392009-08-22 11:39:46 +00005690 if( p->pUnused ){
5691 p->pUnused->fd = fd;
5692 p->pUnused->flags = flags;
5693 }
5694
danielk1977b4b47412007-08-17 15:53:36 +00005695 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005696#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005697 zPath = zName;
5698#else
drh036ac7f2011-08-08 23:18:05 +00005699 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005700#endif
danielk1977b4b47412007-08-17 15:53:36 +00005701 }
drh41022642008-11-21 00:24:42 +00005702#if SQLITE_ENABLE_LOCKING_STYLE
5703 else{
dan08da86a2009-08-21 17:18:03 +00005704 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005705 }
5706#endif
5707
drhda0e7682008-07-30 15:27:54 +00005708 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005709
drh7ed97b92010-01-20 13:07:21 +00005710
5711#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005712 if( fstatfs(fd, &fsInfo) == -1 ){
5713 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005714 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005715 return SQLITE_IOERR_ACCESS;
5716 }
5717 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5718 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5719 }
5720#endif
drhc02a43a2012-01-10 23:18:38 +00005721
5722 /* Set up appropriate ctrlFlags */
5723 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5724 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5725 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5726 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5727 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5728
drh7ed97b92010-01-20 13:07:21 +00005729#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005730#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005731 isAutoProxy = 1;
5732#endif
5733 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005734 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5735 int useProxy = 0;
5736
dan08da86a2009-08-21 17:18:03 +00005737 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5738 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005739 if( envforce!=NULL ){
5740 useProxy = atoi(envforce)>0;
5741 }else{
aswiftaebf4132008-11-21 00:10:35 +00005742 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005743 /* In theory, the close(fd) call is sub-optimal. If the file opened
5744 ** with fd is a database file, and there are other connections open
5745 ** on that file that are currently holding advisory locks on it,
5746 ** then the call to close() will cancel those locks. In practice,
5747 ** we're assuming that statfs() doesn't fail very often. At least
5748 ** not while other file descriptors opened by the same process on
5749 ** the same file are working. */
5750 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005751 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005752 rc = SQLITE_IOERR_ACCESS;
5753 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005754 }
5755 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5756 }
5757 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005758 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005759 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005760 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005761 if( rc!=SQLITE_OK ){
5762 /* Use unixClose to clean up the resources added in fillInUnixFile
5763 ** and clear all the structure's references. Specifically,
5764 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5765 */
5766 unixClose(pFile);
5767 return rc;
5768 }
aswiftaebf4132008-11-21 00:10:35 +00005769 }
dane946c392009-08-22 11:39:46 +00005770 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005771 }
5772 }
5773#endif
5774
drhc02a43a2012-01-10 23:18:38 +00005775 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5776
dane946c392009-08-22 11:39:46 +00005777open_finished:
5778 if( rc!=SQLITE_OK ){
5779 sqlite3_free(p->pUnused);
5780 }
5781 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005782}
5783
dane946c392009-08-22 11:39:46 +00005784
danielk1977b4b47412007-08-17 15:53:36 +00005785/*
danielk1977fee2d252007-08-18 10:59:19 +00005786** Delete the file at zPath. If the dirSync argument is true, fsync()
5787** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005788*/
drh6b9d6dd2008-12-03 19:34:47 +00005789static int unixDelete(
5790 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5791 const char *zPath, /* Name of file to be deleted */
5792 int dirSync /* If true, fsync() directory after deleting file */
5793){
danielk1977fee2d252007-08-18 10:59:19 +00005794 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005795 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005796 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005797 if( osUnlink(zPath)==(-1) ){
5798 if( errno==ENOENT ){
5799 rc = SQLITE_IOERR_DELETE_NOENT;
5800 }else{
drhb4308162012-11-09 21:40:02 +00005801 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005802 }
drhb4308162012-11-09 21:40:02 +00005803 return rc;
drh5d4feff2010-07-14 01:45:22 +00005804 }
danielk1977d39fa702008-10-16 13:27:40 +00005805#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005806 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005807 int fd;
drh90315a22011-08-10 01:52:12 +00005808 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005809 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005810#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005811 if( fsync(fd)==-1 )
5812#else
5813 if( fsync(fd) )
5814#endif
5815 {
dane18d4952011-02-21 11:46:24 +00005816 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005817 }
drh0e9365c2011-03-02 02:08:13 +00005818 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005819 }else if( rc==SQLITE_CANTOPEN ){
5820 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005821 }
5822 }
danielk1977d138dd82008-10-15 16:02:48 +00005823#endif
danielk1977fee2d252007-08-18 10:59:19 +00005824 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005825}
5826
danielk197790949c22007-08-17 16:50:38 +00005827/*
mistachkin48864df2013-03-21 21:20:32 +00005828** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005829** test performed depends on the value of flags:
5830**
5831** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5832** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5833** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5834**
5835** Otherwise return 0.
5836*/
danielk1977861f7452008-06-05 11:39:11 +00005837static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005838 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5839 const char *zPath, /* Path of the file to examine */
5840 int flags, /* What do we want to learn about the zPath file? */
5841 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005842){
rse25c0d1a2007-09-20 08:38:14 +00005843 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005844 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005845 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005846 switch( flags ){
5847 case SQLITE_ACCESS_EXISTS:
5848 amode = F_OK;
5849 break;
5850 case SQLITE_ACCESS_READWRITE:
5851 amode = W_OK|R_OK;
5852 break;
drh50d3f902007-08-27 21:10:36 +00005853 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005854 amode = R_OK;
5855 break;
5856
5857 default:
5858 assert(!"Invalid flags argument");
5859 }
drh99ab3b12011-03-02 15:09:07 +00005860 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005861 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5862 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005863 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005864 *pResOut = 0;
5865 }
5866 }
danielk1977861f7452008-06-05 11:39:11 +00005867 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005868}
5869
danielk1977b4b47412007-08-17 15:53:36 +00005870
5871/*
5872** Turn a relative pathname into a full pathname. The relative path
5873** is stored as a nul-terminated string in the buffer pointed to by
5874** zPath.
5875**
5876** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5877** (in this case, MAX_PATHNAME bytes). The full-path is written to
5878** this buffer before returning.
5879*/
danielk1977adfb9b02007-09-17 07:02:56 +00005880static int unixFullPathname(
5881 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5882 const char *zPath, /* Possibly relative input path */
5883 int nOut, /* Size of output buffer in bytes */
5884 char *zOut /* Output buffer */
5885){
danielk1977843e65f2007-09-01 16:16:15 +00005886
5887 /* It's odd to simulate an io-error here, but really this is just
5888 ** using the io-error infrastructure to test that SQLite handles this
5889 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005890 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005891 */
5892 SimulateIOError( return SQLITE_ERROR );
5893
drh153c62c2007-08-24 03:51:33 +00005894 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005895 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005896
drh3c7f2dc2007-12-06 13:26:20 +00005897 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005898 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005899 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005900 }else{
5901 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005902 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005903 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005904 }
drhea678832008-12-10 19:26:22 +00005905 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005906 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005907 }
5908 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005909}
5910
drh0ccebe72005-06-07 22:22:50 +00005911
drh761df872006-12-21 01:29:22 +00005912#ifndef SQLITE_OMIT_LOAD_EXTENSION
5913/*
5914** Interfaces for opening a shared library, finding entry points
5915** within the shared library, and closing the shared library.
5916*/
5917#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005918static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5919 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005920 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5921}
danielk197795c8a542007-09-01 06:51:27 +00005922
5923/*
5924** SQLite calls this function immediately after a call to unixDlSym() or
5925** unixDlOpen() fails (returns a null pointer). If a more detailed error
5926** message is available, it is written to zBufOut. If no error message
5927** is available, zBufOut is left unmodified and SQLite uses a default
5928** error message.
5929*/
danielk1977397d65f2008-11-19 11:35:39 +00005930static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005931 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005932 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005933 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005934 zErr = dlerror();
5935 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005936 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005937 }
drh6c7d5c52008-11-21 20:32:33 +00005938 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005939}
drh1875f7a2008-12-08 18:19:17 +00005940static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5941 /*
5942 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5943 ** cast into a pointer to a function. And yet the library dlsym() routine
5944 ** returns a void* which is really a pointer to a function. So how do we
5945 ** use dlsym() with -pedantic-errors?
5946 **
5947 ** Variable x below is defined to be a pointer to a function taking
5948 ** parameters void* and const char* and returning a pointer to a function.
5949 ** We initialize x by assigning it a pointer to the dlsym() function.
5950 ** (That assignment requires a cast.) Then we call the function that
5951 ** x points to.
5952 **
5953 ** This work-around is unlikely to work correctly on any system where
5954 ** you really cannot cast a function pointer into void*. But then, on the
5955 ** other hand, dlsym() will not work on such a system either, so we have
5956 ** not really lost anything.
5957 */
5958 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005959 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005960 x = (void(*(*)(void*,const char*))(void))dlsym;
5961 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005962}
danielk1977397d65f2008-11-19 11:35:39 +00005963static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5964 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005965 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005966}
danielk1977b4b47412007-08-17 15:53:36 +00005967#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5968 #define unixDlOpen 0
5969 #define unixDlError 0
5970 #define unixDlSym 0
5971 #define unixDlClose 0
5972#endif
5973
5974/*
danielk197790949c22007-08-17 16:50:38 +00005975** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005976*/
danielk1977397d65f2008-11-19 11:35:39 +00005977static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5978 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005979 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005980
drhbbd42a62004-05-22 17:41:58 +00005981 /* We have to initialize zBuf to prevent valgrind from reporting
5982 ** errors. The reports issued by valgrind are incorrect - we would
5983 ** prefer that the randomness be increased by making use of the
5984 ** uninitialized space in zBuf - but valgrind errors tend to worry
5985 ** some users. Rather than argue, it seems easier just to initialize
5986 ** the whole array and silence valgrind, even if that means less randomness
5987 ** in the random seed.
5988 **
5989 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005990 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005991 ** tests repeatable.
5992 */
danielk1977b4b47412007-08-17 15:53:36 +00005993 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005994#if !defined(SQLITE_TEST)
5995 {
drhc18b4042012-02-10 03:10:27 +00005996 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005997 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005998 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005999 time_t t;
6000 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006001 memcpy(zBuf, &t, sizeof(t));
6002 pid = getpid();
6003 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00006004 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00006005 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00006006 }else{
drhc18b4042012-02-10 03:10:27 +00006007 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006008 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006009 }
drhbbd42a62004-05-22 17:41:58 +00006010 }
6011#endif
drh72cbd072008-10-14 17:58:38 +00006012 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006013}
6014
danielk1977b4b47412007-08-17 15:53:36 +00006015
drhbbd42a62004-05-22 17:41:58 +00006016/*
6017** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006018** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006019** The return value is the number of microseconds of sleep actually
6020** requested from the underlying operating system, a number which
6021** might be greater than or equal to the argument, but not less
6022** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006023*/
danielk1977397d65f2008-11-19 11:35:39 +00006024static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006025#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006026 struct timespec sp;
6027
6028 sp.tv_sec = microseconds / 1000000;
6029 sp.tv_nsec = (microseconds % 1000000) * 1000;
6030 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006031 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006032 return microseconds;
6033#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006034 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006035 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006036 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006037#else
danielk1977b4b47412007-08-17 15:53:36 +00006038 int seconds = (microseconds+999999)/1000000;
6039 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006040 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006041 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006042#endif
drh88f474a2006-01-02 20:00:12 +00006043}
6044
6045/*
drh6b9d6dd2008-12-03 19:34:47 +00006046** The following variable, if set to a non-zero value, is interpreted as
6047** the number of seconds since 1970 and is used to set the result of
6048** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006049*/
6050#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006051int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006052#endif
6053
6054/*
drhb7e8ea22010-05-03 14:32:30 +00006055** Find the current time (in Universal Coordinated Time). Write into *piNow
6056** the current time and date as a Julian Day number times 86_400_000. In
6057** other words, write into *piNow the number of milliseconds since the Julian
6058** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6059** proleptic Gregorian calendar.
6060**
drh31702252011-10-12 23:13:43 +00006061** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6062** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006063*/
6064static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6065 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006066 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006067#if defined(NO_GETTOD)
6068 time_t t;
6069 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006070 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006071#elif OS_VXWORKS
6072 struct timespec sNow;
6073 clock_gettime(CLOCK_REALTIME, &sNow);
6074 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6075#else
6076 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006077 if( gettimeofday(&sNow, 0)==0 ){
6078 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6079 }else{
6080 rc = SQLITE_ERROR;
6081 }
drhb7e8ea22010-05-03 14:32:30 +00006082#endif
6083
6084#ifdef SQLITE_TEST
6085 if( sqlite3_current_time ){
6086 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6087 }
6088#endif
6089 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006090 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006091}
6092
6093/*
drhbbd42a62004-05-22 17:41:58 +00006094** Find the current time (in Universal Coordinated Time). Write the
6095** current time and date as a Julian Day number into *prNow and
6096** return 0. Return 1 if the time and date cannot be found.
6097*/
danielk1977397d65f2008-11-19 11:35:39 +00006098static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006099 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006100 int rc;
drhff828942010-06-26 21:34:06 +00006101 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006102 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006103 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006104 return rc;
drhbbd42a62004-05-22 17:41:58 +00006105}
danielk1977b4b47412007-08-17 15:53:36 +00006106
drh6b9d6dd2008-12-03 19:34:47 +00006107/*
6108** We added the xGetLastError() method with the intention of providing
6109** better low-level error messages when operating-system problems come up
6110** during SQLite operation. But so far, none of that has been implemented
6111** in the core. So this routine is never called. For now, it is merely
6112** a place-holder.
6113*/
danielk1977397d65f2008-11-19 11:35:39 +00006114static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6115 UNUSED_PARAMETER(NotUsed);
6116 UNUSED_PARAMETER(NotUsed2);
6117 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006118 return 0;
6119}
6120
drhf2424c52010-04-26 00:04:55 +00006121
6122/*
drh734c9862008-11-28 15:37:20 +00006123************************ End of sqlite3_vfs methods ***************************
6124******************************************************************************/
6125
drh715ff302008-12-03 22:32:44 +00006126/******************************************************************************
6127************************** Begin Proxy Locking ********************************
6128**
6129** Proxy locking is a "uber-locking-method" in this sense: It uses the
6130** other locking methods on secondary lock files. Proxy locking is a
6131** meta-layer over top of the primitive locking implemented above. For
6132** this reason, the division that implements of proxy locking is deferred
6133** until late in the file (here) after all of the other I/O methods have
6134** been defined - so that the primitive locking methods are available
6135** as services to help with the implementation of proxy locking.
6136**
6137****
6138**
6139** The default locking schemes in SQLite use byte-range locks on the
6140** database file to coordinate safe, concurrent access by multiple readers
6141** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6142** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6143** as POSIX read & write locks over fixed set of locations (via fsctl),
6144** on AFP and SMB only exclusive byte-range locks are available via fsctl
6145** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6146** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6147** address in the shared range is taken for a SHARED lock, the entire
6148** shared range is taken for an EXCLUSIVE lock):
6149**
drhf2f105d2012-08-20 15:53:54 +00006150** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006151** RESERVED_BYTE 0x40000001
6152** SHARED_RANGE 0x40000002 -> 0x40000200
6153**
6154** This works well on the local file system, but shows a nearly 100x
6155** slowdown in read performance on AFP because the AFP client disables
6156** the read cache when byte-range locks are present. Enabling the read
6157** cache exposes a cache coherency problem that is present on all OS X
6158** supported network file systems. NFS and AFP both observe the
6159** close-to-open semantics for ensuring cache coherency
6160** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6161** address the requirements for concurrent database access by multiple
6162** readers and writers
6163** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6164**
6165** To address the performance and cache coherency issues, proxy file locking
6166** changes the way database access is controlled by limiting access to a
6167** single host at a time and moving file locks off of the database file
6168** and onto a proxy file on the local file system.
6169**
6170**
6171** Using proxy locks
6172** -----------------
6173**
6174** C APIs
6175**
6176** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6177** <proxy_path> | ":auto:");
6178** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6179**
6180**
6181** SQL pragmas
6182**
6183** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6184** PRAGMA [database.]lock_proxy_file
6185**
6186** Specifying ":auto:" means that if there is a conch file with a matching
6187** host ID in it, the proxy path in the conch file will be used, otherwise
6188** a proxy path based on the user's temp dir
6189** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6190** actual proxy file name is generated from the name and path of the
6191** database file. For example:
6192**
6193** For database path "/Users/me/foo.db"
6194** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6195**
6196** Once a lock proxy is configured for a database connection, it can not
6197** be removed, however it may be switched to a different proxy path via
6198** the above APIs (assuming the conch file is not being held by another
6199** connection or process).
6200**
6201**
6202** How proxy locking works
6203** -----------------------
6204**
6205** Proxy file locking relies primarily on two new supporting files:
6206**
6207** * conch file to limit access to the database file to a single host
6208** at a time
6209**
6210** * proxy file to act as a proxy for the advisory locks normally
6211** taken on the database
6212**
6213** The conch file - to use a proxy file, sqlite must first "hold the conch"
6214** by taking an sqlite-style shared lock on the conch file, reading the
6215** contents and comparing the host's unique host ID (see below) and lock
6216** proxy path against the values stored in the conch. The conch file is
6217** stored in the same directory as the database file and the file name
6218** is patterned after the database file name as ".<databasename>-conch".
6219** If the conch file does not exist, or it's contents do not match the
6220** host ID and/or proxy path, then the lock is escalated to an exclusive
6221** lock and the conch file contents is updated with the host ID and proxy
6222** path and the lock is downgraded to a shared lock again. If the conch
6223** is held by another process (with a shared lock), the exclusive lock
6224** will fail and SQLITE_BUSY is returned.
6225**
6226** The proxy file - a single-byte file used for all advisory file locks
6227** normally taken on the database file. This allows for safe sharing
6228** of the database file for multiple readers and writers on the same
6229** host (the conch ensures that they all use the same local lock file).
6230**
drh715ff302008-12-03 22:32:44 +00006231** Requesting the lock proxy does not immediately take the conch, it is
6232** only taken when the first request to lock database file is made.
6233** This matches the semantics of the traditional locking behavior, where
6234** opening a connection to a database file does not take a lock on it.
6235** The shared lock and an open file descriptor are maintained until
6236** the connection to the database is closed.
6237**
6238** The proxy file and the lock file are never deleted so they only need
6239** to be created the first time they are used.
6240**
6241** Configuration options
6242** ---------------------
6243**
6244** SQLITE_PREFER_PROXY_LOCKING
6245**
6246** Database files accessed on non-local file systems are
6247** automatically configured for proxy locking, lock files are
6248** named automatically using the same logic as
6249** PRAGMA lock_proxy_file=":auto:"
6250**
6251** SQLITE_PROXY_DEBUG
6252**
6253** Enables the logging of error messages during host id file
6254** retrieval and creation
6255**
drh715ff302008-12-03 22:32:44 +00006256** LOCKPROXYDIR
6257**
6258** Overrides the default directory used for lock proxy files that
6259** are named automatically via the ":auto:" setting
6260**
6261** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6262**
6263** Permissions to use when creating a directory for storing the
6264** lock proxy files, only used when LOCKPROXYDIR is not set.
6265**
6266**
6267** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6268** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6269** force proxy locking to be used for every database file opened, and 0
6270** will force automatic proxy locking to be disabled for all database
6271** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6272** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6273*/
6274
6275/*
6276** Proxy locking is only available on MacOSX
6277*/
drhd2cb50b2009-01-09 21:41:17 +00006278#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006279
drh715ff302008-12-03 22:32:44 +00006280/*
6281** The proxyLockingContext has the path and file structures for the remote
6282** and local proxy files in it
6283*/
6284typedef struct proxyLockingContext proxyLockingContext;
6285struct proxyLockingContext {
6286 unixFile *conchFile; /* Open conch file */
6287 char *conchFilePath; /* Name of the conch file */
6288 unixFile *lockProxy; /* Open proxy lock file */
6289 char *lockProxyPath; /* Name of the proxy lock file */
6290 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006291 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006292 void *oldLockingContext; /* Original lockingcontext to restore on close */
6293 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6294};
6295
drh7ed97b92010-01-20 13:07:21 +00006296/*
6297** The proxy lock file path for the database at dbPath is written into lPath,
6298** which must point to valid, writable memory large enough for a maxLen length
6299** file path.
drh715ff302008-12-03 22:32:44 +00006300*/
drh715ff302008-12-03 22:32:44 +00006301static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6302 int len;
6303 int dbLen;
6304 int i;
6305
6306#ifdef LOCKPROXYDIR
6307 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6308#else
6309# ifdef _CS_DARWIN_USER_TEMP_DIR
6310 {
drh7ed97b92010-01-20 13:07:21 +00006311 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006312 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6313 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006314 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006315 }
drh7ed97b92010-01-20 13:07:21 +00006316 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006317 }
6318# else
6319 len = strlcpy(lPath, "/tmp/", maxLen);
6320# endif
6321#endif
6322
6323 if( lPath[len-1]!='/' ){
6324 len = strlcat(lPath, "/", maxLen);
6325 }
6326
6327 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006328 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006329 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006330 char c = dbPath[i];
6331 lPath[i+len] = (c=='/')?'_':c;
6332 }
6333 lPath[i+len]='\0';
6334 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006335 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006336 return SQLITE_OK;
6337}
6338
drh7ed97b92010-01-20 13:07:21 +00006339/*
6340 ** Creates the lock file and any missing directories in lockPath
6341 */
6342static int proxyCreateLockPath(const char *lockPath){
6343 int i, len;
6344 char buf[MAXPATHLEN];
6345 int start = 0;
6346
6347 assert(lockPath!=NULL);
6348 /* try to create all the intermediate directories */
6349 len = (int)strlen(lockPath);
6350 buf[0] = lockPath[0];
6351 for( i=1; i<len; i++ ){
6352 if( lockPath[i] == '/' && (i - start > 0) ){
6353 /* only mkdir if leaf dir != "." or "/" or ".." */
6354 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6355 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6356 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006357 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006358 int err=errno;
6359 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006360 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006361 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006362 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006363 return err;
6364 }
6365 }
6366 }
6367 start=i+1;
6368 }
6369 buf[i] = lockPath[i];
6370 }
drh308c2a52010-05-14 11:30:18 +00006371 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006372 return 0;
6373}
6374
drh715ff302008-12-03 22:32:44 +00006375/*
6376** Create a new VFS file descriptor (stored in memory obtained from
6377** sqlite3_malloc) and open the file named "path" in the file descriptor.
6378**
6379** The caller is responsible not only for closing the file descriptor
6380** but also for freeing the memory associated with the file descriptor.
6381*/
drh7ed97b92010-01-20 13:07:21 +00006382static int proxyCreateUnixFile(
6383 const char *path, /* path for the new unixFile */
6384 unixFile **ppFile, /* unixFile created and returned by ref */
6385 int islockfile /* if non zero missing dirs will be created */
6386) {
6387 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006388 unixFile *pNew;
6389 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006390 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006391 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006392 int terrno = 0;
6393 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006394
drh7ed97b92010-01-20 13:07:21 +00006395 /* 1. first try to open/create the file
6396 ** 2. if that fails, and this is a lock file (not-conch), try creating
6397 ** the parent directories and then try again.
6398 ** 3. if that fails, try to open the file read-only
6399 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6400 */
6401 pUnused = findReusableFd(path, openFlags);
6402 if( pUnused ){
6403 fd = pUnused->fd;
6404 }else{
6405 pUnused = sqlite3_malloc(sizeof(*pUnused));
6406 if( !pUnused ){
6407 return SQLITE_NOMEM;
6408 }
6409 }
6410 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006411 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006412 terrno = errno;
6413 if( fd<0 && errno==ENOENT && islockfile ){
6414 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006415 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006416 }
6417 }
6418 }
6419 if( fd<0 ){
6420 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006421 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006422 terrno = errno;
6423 }
6424 if( fd<0 ){
6425 if( islockfile ){
6426 return SQLITE_BUSY;
6427 }
6428 switch (terrno) {
6429 case EACCES:
6430 return SQLITE_PERM;
6431 case EIO:
6432 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6433 default:
drh9978c972010-02-23 17:36:32 +00006434 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006435 }
6436 }
6437
6438 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6439 if( pNew==NULL ){
6440 rc = SQLITE_NOMEM;
6441 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006442 }
6443 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006444 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006445 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006446 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006447 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006448 pUnused->fd = fd;
6449 pUnused->flags = openFlags;
6450 pNew->pUnused = pUnused;
6451
drhc02a43a2012-01-10 23:18:38 +00006452 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006453 if( rc==SQLITE_OK ){
6454 *ppFile = pNew;
6455 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006456 }
drh7ed97b92010-01-20 13:07:21 +00006457end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006458 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006459 sqlite3_free(pNew);
6460 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006461 return rc;
6462}
6463
drh7ed97b92010-01-20 13:07:21 +00006464#ifdef SQLITE_TEST
6465/* simulate multiple hosts by creating unique hostid file paths */
6466int sqlite3_hostid_num = 0;
6467#endif
6468
6469#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6470
drh0ab216a2010-07-02 17:10:40 +00006471/* Not always defined in the headers as it ought to be */
6472extern int gethostuuid(uuid_t id, const struct timespec *wait);
6473
drh7ed97b92010-01-20 13:07:21 +00006474/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6475** bytes of writable memory.
6476*/
6477static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006478 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6479 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006480#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6481 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006482 {
6483 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6484 if( gethostuuid(pHostID, &timeout) ){
6485 int err = errno;
6486 if( pError ){
6487 *pError = err;
6488 }
6489 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006490 }
drh7ed97b92010-01-20 13:07:21 +00006491 }
drh3d4435b2011-08-26 20:55:50 +00006492#else
6493 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006494#endif
drh7ed97b92010-01-20 13:07:21 +00006495#ifdef SQLITE_TEST
6496 /* simulate multiple hosts by creating unique hostid file paths */
6497 if( sqlite3_hostid_num != 0){
6498 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6499 }
6500#endif
6501
6502 return SQLITE_OK;
6503}
6504
6505/* The conch file contains the header, host id and lock file path
6506 */
6507#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6508#define PROXY_HEADERLEN 1 /* conch file header length */
6509#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6510#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6511
6512/*
6513** Takes an open conch file, copies the contents to a new path and then moves
6514** it back. The newly created file's file descriptor is assigned to the
6515** conch file structure and finally the original conch file descriptor is
6516** closed. Returns zero if successful.
6517*/
6518static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6519 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6520 unixFile *conchFile = pCtx->conchFile;
6521 char tPath[MAXPATHLEN];
6522 char buf[PROXY_MAXCONCHLEN];
6523 char *cPath = pCtx->conchFilePath;
6524 size_t readLen = 0;
6525 size_t pathLen = 0;
6526 char errmsg[64] = "";
6527 int fd = -1;
6528 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006529 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006530
6531 /* create a new path by replace the trailing '-conch' with '-break' */
6532 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6533 if( pathLen>MAXPATHLEN || pathLen<6 ||
6534 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006535 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006536 goto end_breaklock;
6537 }
6538 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006539 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006540 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006541 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006542 goto end_breaklock;
6543 }
6544 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006545 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006546 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006547 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006548 goto end_breaklock;
6549 }
drhe562be52011-03-02 18:01:10 +00006550 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006551 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006552 goto end_breaklock;
6553 }
6554 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006555 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006556 goto end_breaklock;
6557 }
6558 rc = 0;
6559 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006560 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006561 conchFile->h = fd;
6562 conchFile->openFlags = O_RDWR | O_CREAT;
6563
6564end_breaklock:
6565 if( rc ){
6566 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006567 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006568 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006569 }
6570 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6571 }
6572 return rc;
6573}
6574
6575/* Take the requested lock on the conch file and break a stale lock if the
6576** host id matches.
6577*/
6578static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6579 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6580 unixFile *conchFile = pCtx->conchFile;
6581 int rc = SQLITE_OK;
6582 int nTries = 0;
6583 struct timespec conchModTime;
6584
drh3d4435b2011-08-26 20:55:50 +00006585 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006586 do {
6587 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6588 nTries ++;
6589 if( rc==SQLITE_BUSY ){
6590 /* If the lock failed (busy):
6591 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6592 * 2nd try: fail if the mod time changed or host id is different, wait
6593 * 10 sec and try again
6594 * 3rd try: break the lock unless the mod time has changed.
6595 */
6596 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006597 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006598 pFile->lastErrno = errno;
6599 return SQLITE_IOERR_LOCK;
6600 }
6601
6602 if( nTries==1 ){
6603 conchModTime = buf.st_mtimespec;
6604 usleep(500000); /* wait 0.5 sec and try the lock again*/
6605 continue;
6606 }
6607
6608 assert( nTries>1 );
6609 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6610 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6611 return SQLITE_BUSY;
6612 }
6613
6614 if( nTries==2 ){
6615 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006616 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006617 if( len<0 ){
6618 pFile->lastErrno = errno;
6619 return SQLITE_IOERR_LOCK;
6620 }
6621 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6622 /* don't break the lock if the host id doesn't match */
6623 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6624 return SQLITE_BUSY;
6625 }
6626 }else{
6627 /* don't break the lock on short read or a version mismatch */
6628 return SQLITE_BUSY;
6629 }
6630 usleep(10000000); /* wait 10 sec and try the lock again */
6631 continue;
6632 }
6633
6634 assert( nTries==3 );
6635 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6636 rc = SQLITE_OK;
6637 if( lockType==EXCLUSIVE_LOCK ){
6638 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6639 }
6640 if( !rc ){
6641 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6642 }
6643 }
6644 }
6645 } while( rc==SQLITE_BUSY && nTries<3 );
6646
6647 return rc;
6648}
6649
6650/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006651** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6652** lockPath means that the lockPath in the conch file will be used if the
6653** host IDs match, or a new lock path will be generated automatically
6654** and written to the conch file.
6655*/
6656static int proxyTakeConch(unixFile *pFile){
6657 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6658
drh7ed97b92010-01-20 13:07:21 +00006659 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006660 return SQLITE_OK;
6661 }else{
6662 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006663 uuid_t myHostID;
6664 int pError = 0;
6665 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006666 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006667 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006668 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006669 int createConch = 0;
6670 int hostIdMatch = 0;
6671 int readLen = 0;
6672 int tryOldLockPath = 0;
6673 int forceNewLockPath = 0;
6674
drh308c2a52010-05-14 11:30:18 +00006675 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6676 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006677
drh7ed97b92010-01-20 13:07:21 +00006678 rc = proxyGetHostID(myHostID, &pError);
6679 if( (rc&0xff)==SQLITE_IOERR ){
6680 pFile->lastErrno = pError;
6681 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006682 }
drh7ed97b92010-01-20 13:07:21 +00006683 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006684 if( rc!=SQLITE_OK ){
6685 goto end_takeconch;
6686 }
drh7ed97b92010-01-20 13:07:21 +00006687 /* read the existing conch file */
6688 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6689 if( readLen<0 ){
6690 /* I/O error: lastErrno set by seekAndRead */
6691 pFile->lastErrno = conchFile->lastErrno;
6692 rc = SQLITE_IOERR_READ;
6693 goto end_takeconch;
6694 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6695 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6696 /* a short read or version format mismatch means we need to create a new
6697 ** conch file.
6698 */
6699 createConch = 1;
6700 }
6701 /* if the host id matches and the lock path already exists in the conch
6702 ** we'll try to use the path there, if we can't open that path, we'll
6703 ** retry with a new auto-generated path
6704 */
6705 do { /* in case we need to try again for an :auto: named lock file */
6706
6707 if( !createConch && !forceNewLockPath ){
6708 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6709 PROXY_HOSTIDLEN);
6710 /* if the conch has data compare the contents */
6711 if( !pCtx->lockProxyPath ){
6712 /* for auto-named local lock file, just check the host ID and we'll
6713 ** use the local lock file path that's already in there
6714 */
6715 if( hostIdMatch ){
6716 size_t pathLen = (readLen - PROXY_PATHINDEX);
6717
6718 if( pathLen>=MAXPATHLEN ){
6719 pathLen=MAXPATHLEN-1;
6720 }
6721 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6722 lockPath[pathLen] = 0;
6723 tempLockPath = lockPath;
6724 tryOldLockPath = 1;
6725 /* create a copy of the lock path if the conch is taken */
6726 goto end_takeconch;
6727 }
6728 }else if( hostIdMatch
6729 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6730 readLen-PROXY_PATHINDEX)
6731 ){
6732 /* conch host and lock path match */
6733 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006734 }
drh7ed97b92010-01-20 13:07:21 +00006735 }
6736
6737 /* if the conch isn't writable and doesn't match, we can't take it */
6738 if( (conchFile->openFlags&O_RDWR) == 0 ){
6739 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006740 goto end_takeconch;
6741 }
drh7ed97b92010-01-20 13:07:21 +00006742
6743 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006744 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006745 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6746 tempLockPath = lockPath;
6747 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006748 }
drh7ed97b92010-01-20 13:07:21 +00006749
6750 /* update conch with host and path (this will fail if other process
6751 ** has a shared lock already), if the host id matches, use the big
6752 ** stick.
drh715ff302008-12-03 22:32:44 +00006753 */
drh7ed97b92010-01-20 13:07:21 +00006754 futimes(conchFile->h, NULL);
6755 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006756 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006757 /* We are trying for an exclusive lock but another thread in this
6758 ** same process is still holding a shared lock. */
6759 rc = SQLITE_BUSY;
6760 } else {
6761 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006762 }
drh715ff302008-12-03 22:32:44 +00006763 }else{
drh7ed97b92010-01-20 13:07:21 +00006764 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006765 }
drh7ed97b92010-01-20 13:07:21 +00006766 if( rc==SQLITE_OK ){
6767 char writeBuffer[PROXY_MAXCONCHLEN];
6768 int writeSize = 0;
6769
6770 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6771 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6772 if( pCtx->lockProxyPath!=NULL ){
6773 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6774 }else{
6775 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6776 }
6777 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006778 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006779 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6780 fsync(conchFile->h);
6781 /* If we created a new conch file (not just updated the contents of a
6782 ** valid conch file), try to match the permissions of the database
6783 */
6784 if( rc==SQLITE_OK && createConch ){
6785 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006786 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006787 if( err==0 ){
6788 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6789 S_IROTH|S_IWOTH);
6790 /* try to match the database file R/W permissions, ignore failure */
6791#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006792 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006793#else
drhff812312011-02-23 13:33:46 +00006794 do{
drhe562be52011-03-02 18:01:10 +00006795 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006796 }while( rc==(-1) && errno==EINTR );
6797 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006798 int code = errno;
6799 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6800 cmode, code, strerror(code));
6801 } else {
6802 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6803 }
6804 }else{
6805 int code = errno;
6806 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6807 err, code, strerror(code));
6808#endif
6809 }
drh715ff302008-12-03 22:32:44 +00006810 }
6811 }
drh7ed97b92010-01-20 13:07:21 +00006812 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6813
6814 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006815 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006816 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006817 int fd;
drh7ed97b92010-01-20 13:07:21 +00006818 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006819 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006820 }
6821 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006822 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006823 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006824 if( fd>=0 ){
6825 pFile->h = fd;
6826 }else{
drh9978c972010-02-23 17:36:32 +00006827 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006828 during locking */
6829 }
6830 }
6831 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6832 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6833 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6834 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6835 /* we couldn't create the proxy lock file with the old lock file path
6836 ** so try again via auto-naming
6837 */
6838 forceNewLockPath = 1;
6839 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006840 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006841 }
6842 }
6843 if( rc==SQLITE_OK ){
6844 /* Need to make a copy of path if we extracted the value
6845 ** from the conch file or the path was allocated on the stack
6846 */
6847 if( tempLockPath ){
6848 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6849 if( !pCtx->lockProxyPath ){
6850 rc = SQLITE_NOMEM;
6851 }
6852 }
6853 }
6854 if( rc==SQLITE_OK ){
6855 pCtx->conchHeld = 1;
6856
6857 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6858 afpLockingContext *afpCtx;
6859 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6860 afpCtx->dbPath = pCtx->lockProxyPath;
6861 }
6862 } else {
6863 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6864 }
drh308c2a52010-05-14 11:30:18 +00006865 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6866 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006867 return rc;
drh308c2a52010-05-14 11:30:18 +00006868 } while (1); /* in case we need to retry the :auto: lock file -
6869 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006870 }
6871}
6872
6873/*
6874** If pFile holds a lock on a conch file, then release that lock.
6875*/
6876static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006877 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006878 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6879 unixFile *conchFile; /* Name of the conch file */
6880
6881 pCtx = (proxyLockingContext *)pFile->lockingContext;
6882 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006883 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006884 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006885 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006886 if( pCtx->conchHeld>0 ){
6887 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6888 }
drh715ff302008-12-03 22:32:44 +00006889 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006890 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6891 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006892 return rc;
6893}
6894
6895/*
6896** Given the name of a database file, compute the name of its conch file.
6897** Store the conch filename in memory obtained from sqlite3_malloc().
6898** Make *pConchPath point to the new name. Return SQLITE_OK on success
6899** or SQLITE_NOMEM if unable to obtain memory.
6900**
6901** The caller is responsible for ensuring that the allocated memory
6902** space is eventually freed.
6903**
6904** *pConchPath is set to NULL if a memory allocation error occurs.
6905*/
6906static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6907 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006908 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006909 char *conchPath; /* buffer in which to construct conch name */
6910
6911 /* Allocate space for the conch filename and initialize the name to
6912 ** the name of the original database file. */
6913 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6914 if( conchPath==0 ){
6915 return SQLITE_NOMEM;
6916 }
6917 memcpy(conchPath, dbPath, len+1);
6918
6919 /* now insert a "." before the last / character */
6920 for( i=(len-1); i>=0; i-- ){
6921 if( conchPath[i]=='/' ){
6922 i++;
6923 break;
6924 }
6925 }
6926 conchPath[i]='.';
6927 while ( i<len ){
6928 conchPath[i+1]=dbPath[i];
6929 i++;
6930 }
6931
6932 /* append the "-conch" suffix to the file */
6933 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006934 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006935
6936 return SQLITE_OK;
6937}
6938
6939
6940/* Takes a fully configured proxy locking-style unix file and switches
6941** the local lock file path
6942*/
6943static int switchLockProxyPath(unixFile *pFile, const char *path) {
6944 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6945 char *oldPath = pCtx->lockProxyPath;
6946 int rc = SQLITE_OK;
6947
drh308c2a52010-05-14 11:30:18 +00006948 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006949 return SQLITE_BUSY;
6950 }
6951
6952 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6953 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6954 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6955 return SQLITE_OK;
6956 }else{
6957 unixFile *lockProxy = pCtx->lockProxy;
6958 pCtx->lockProxy=NULL;
6959 pCtx->conchHeld = 0;
6960 if( lockProxy!=NULL ){
6961 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6962 if( rc ) return rc;
6963 sqlite3_free(lockProxy);
6964 }
6965 sqlite3_free(oldPath);
6966 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6967 }
6968
6969 return rc;
6970}
6971
6972/*
6973** pFile is a file that has been opened by a prior xOpen call. dbPath
6974** is a string buffer at least MAXPATHLEN+1 characters in size.
6975**
6976** This routine find the filename associated with pFile and writes it
6977** int dbPath.
6978*/
6979static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006980#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006981 if( pFile->pMethod == &afpIoMethods ){
6982 /* afp style keeps a reference to the db path in the filePath field
6983 ** of the struct */
drhea678832008-12-10 19:26:22 +00006984 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006985 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6986 } else
drh715ff302008-12-03 22:32:44 +00006987#endif
6988 if( pFile->pMethod == &dotlockIoMethods ){
6989 /* dot lock style uses the locking context to store the dot lock
6990 ** file path */
6991 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6992 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6993 }else{
6994 /* all other styles use the locking context to store the db file path */
6995 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006996 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006997 }
6998 return SQLITE_OK;
6999}
7000
7001/*
7002** Takes an already filled in unix file and alters it so all file locking
7003** will be performed on the local proxy lock file. The following fields
7004** are preserved in the locking context so that they can be restored and
7005** the unix structure properly cleaned up at close time:
7006** ->lockingContext
7007** ->pMethod
7008*/
7009static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7010 proxyLockingContext *pCtx;
7011 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7012 char *lockPath=NULL;
7013 int rc = SQLITE_OK;
7014
drh308c2a52010-05-14 11:30:18 +00007015 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007016 return SQLITE_BUSY;
7017 }
7018 proxyGetDbPathForUnixFile(pFile, dbPath);
7019 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7020 lockPath=NULL;
7021 }else{
7022 lockPath=(char *)path;
7023 }
7024
drh308c2a52010-05-14 11:30:18 +00007025 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7026 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007027
7028 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7029 if( pCtx==0 ){
7030 return SQLITE_NOMEM;
7031 }
7032 memset(pCtx, 0, sizeof(*pCtx));
7033
7034 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7035 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007036 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7037 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7038 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7039 ** (c) the file system is read-only, then enable no-locking access.
7040 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7041 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7042 */
7043 struct statfs fsInfo;
7044 struct stat conchInfo;
7045 int goLockless = 0;
7046
drh99ab3b12011-03-02 15:09:07 +00007047 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007048 int err = errno;
7049 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7050 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7051 }
7052 }
7053 if( goLockless ){
7054 pCtx->conchHeld = -1; /* read only FS/ lockless */
7055 rc = SQLITE_OK;
7056 }
7057 }
drh715ff302008-12-03 22:32:44 +00007058 }
7059 if( rc==SQLITE_OK && lockPath ){
7060 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7061 }
7062
7063 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007064 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7065 if( pCtx->dbPath==NULL ){
7066 rc = SQLITE_NOMEM;
7067 }
7068 }
7069 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007070 /* all memory is allocated, proxys are created and assigned,
7071 ** switch the locking context and pMethod then return.
7072 */
drh715ff302008-12-03 22:32:44 +00007073 pCtx->oldLockingContext = pFile->lockingContext;
7074 pFile->lockingContext = pCtx;
7075 pCtx->pOldMethod = pFile->pMethod;
7076 pFile->pMethod = &proxyIoMethods;
7077 }else{
7078 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007079 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007080 sqlite3_free(pCtx->conchFile);
7081 }
drhd56b1212010-08-11 06:14:15 +00007082 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007083 sqlite3_free(pCtx->conchFilePath);
7084 sqlite3_free(pCtx);
7085 }
drh308c2a52010-05-14 11:30:18 +00007086 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7087 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007088 return rc;
7089}
7090
7091
7092/*
7093** This routine handles sqlite3_file_control() calls that are specific
7094** to proxy locking.
7095*/
7096static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7097 switch( op ){
7098 case SQLITE_GET_LOCKPROXYFILE: {
7099 unixFile *pFile = (unixFile*)id;
7100 if( pFile->pMethod == &proxyIoMethods ){
7101 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7102 proxyTakeConch(pFile);
7103 if( pCtx->lockProxyPath ){
7104 *(const char **)pArg = pCtx->lockProxyPath;
7105 }else{
7106 *(const char **)pArg = ":auto: (not held)";
7107 }
7108 } else {
7109 *(const char **)pArg = NULL;
7110 }
7111 return SQLITE_OK;
7112 }
7113 case SQLITE_SET_LOCKPROXYFILE: {
7114 unixFile *pFile = (unixFile*)id;
7115 int rc = SQLITE_OK;
7116 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7117 if( pArg==NULL || (const char *)pArg==0 ){
7118 if( isProxyStyle ){
7119 /* turn off proxy locking - not supported */
7120 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7121 }else{
7122 /* turn off proxy locking - already off - NOOP */
7123 rc = SQLITE_OK;
7124 }
7125 }else{
7126 const char *proxyPath = (const char *)pArg;
7127 if( isProxyStyle ){
7128 proxyLockingContext *pCtx =
7129 (proxyLockingContext*)pFile->lockingContext;
7130 if( !strcmp(pArg, ":auto:")
7131 || (pCtx->lockProxyPath &&
7132 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7133 ){
7134 rc = SQLITE_OK;
7135 }else{
7136 rc = switchLockProxyPath(pFile, proxyPath);
7137 }
7138 }else{
7139 /* turn on proxy file locking */
7140 rc = proxyTransformUnixFile(pFile, proxyPath);
7141 }
7142 }
7143 return rc;
7144 }
7145 default: {
7146 assert( 0 ); /* The call assures that only valid opcodes are sent */
7147 }
7148 }
7149 /*NOTREACHED*/
7150 return SQLITE_ERROR;
7151}
7152
7153/*
7154** Within this division (the proxying locking implementation) the procedures
7155** above this point are all utilities. The lock-related methods of the
7156** proxy-locking sqlite3_io_method object follow.
7157*/
7158
7159
7160/*
7161** This routine checks if there is a RESERVED lock held on the specified
7162** file by this or any other process. If such a lock is held, set *pResOut
7163** to a non-zero value otherwise *pResOut is set to zero. The return value
7164** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7165*/
7166static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7167 unixFile *pFile = (unixFile*)id;
7168 int rc = proxyTakeConch(pFile);
7169 if( rc==SQLITE_OK ){
7170 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007171 if( pCtx->conchHeld>0 ){
7172 unixFile *proxy = pCtx->lockProxy;
7173 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7174 }else{ /* conchHeld < 0 is lockless */
7175 pResOut=0;
7176 }
drh715ff302008-12-03 22:32:44 +00007177 }
7178 return rc;
7179}
7180
7181/*
drh308c2a52010-05-14 11:30:18 +00007182** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007183** of the following:
7184**
7185** (1) SHARED_LOCK
7186** (2) RESERVED_LOCK
7187** (3) PENDING_LOCK
7188** (4) EXCLUSIVE_LOCK
7189**
7190** Sometimes when requesting one lock state, additional lock states
7191** are inserted in between. The locking might fail on one of the later
7192** transitions leaving the lock state different from what it started but
7193** still short of its goal. The following chart shows the allowed
7194** transitions and the inserted intermediate states:
7195**
7196** UNLOCKED -> SHARED
7197** SHARED -> RESERVED
7198** SHARED -> (PENDING) -> EXCLUSIVE
7199** RESERVED -> (PENDING) -> EXCLUSIVE
7200** PENDING -> EXCLUSIVE
7201**
7202** This routine will only increase a lock. Use the sqlite3OsUnlock()
7203** routine to lower a locking level.
7204*/
drh308c2a52010-05-14 11:30:18 +00007205static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007206 unixFile *pFile = (unixFile*)id;
7207 int rc = proxyTakeConch(pFile);
7208 if( rc==SQLITE_OK ){
7209 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007210 if( pCtx->conchHeld>0 ){
7211 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007212 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7213 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007214 }else{
7215 /* conchHeld < 0 is lockless */
7216 }
drh715ff302008-12-03 22:32:44 +00007217 }
7218 return rc;
7219}
7220
7221
7222/*
drh308c2a52010-05-14 11:30:18 +00007223** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007224** must be either NO_LOCK or SHARED_LOCK.
7225**
7226** If the locking level of the file descriptor is already at or below
7227** the requested locking level, this routine is a no-op.
7228*/
drh308c2a52010-05-14 11:30:18 +00007229static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007230 unixFile *pFile = (unixFile*)id;
7231 int rc = proxyTakeConch(pFile);
7232 if( rc==SQLITE_OK ){
7233 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007234 if( pCtx->conchHeld>0 ){
7235 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007236 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7237 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007238 }else{
7239 /* conchHeld < 0 is lockless */
7240 }
drh715ff302008-12-03 22:32:44 +00007241 }
7242 return rc;
7243}
7244
7245/*
7246** Close a file that uses proxy locks.
7247*/
7248static int proxyClose(sqlite3_file *id) {
7249 if( id ){
7250 unixFile *pFile = (unixFile*)id;
7251 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7252 unixFile *lockProxy = pCtx->lockProxy;
7253 unixFile *conchFile = pCtx->conchFile;
7254 int rc = SQLITE_OK;
7255
7256 if( lockProxy ){
7257 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7258 if( rc ) return rc;
7259 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7260 if( rc ) return rc;
7261 sqlite3_free(lockProxy);
7262 pCtx->lockProxy = 0;
7263 }
7264 if( conchFile ){
7265 if( pCtx->conchHeld ){
7266 rc = proxyReleaseConch(pFile);
7267 if( rc ) return rc;
7268 }
7269 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7270 if( rc ) return rc;
7271 sqlite3_free(conchFile);
7272 }
drhd56b1212010-08-11 06:14:15 +00007273 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007274 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007275 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007276 /* restore the original locking context and pMethod then close it */
7277 pFile->lockingContext = pCtx->oldLockingContext;
7278 pFile->pMethod = pCtx->pOldMethod;
7279 sqlite3_free(pCtx);
7280 return pFile->pMethod->xClose(id);
7281 }
7282 return SQLITE_OK;
7283}
7284
7285
7286
drhd2cb50b2009-01-09 21:41:17 +00007287#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007288/*
7289** The proxy locking style is intended for use with AFP filesystems.
7290** And since AFP is only supported on MacOSX, the proxy locking is also
7291** restricted to MacOSX.
7292**
7293**
7294******************* End of the proxy lock implementation **********************
7295******************************************************************************/
7296
drh734c9862008-11-28 15:37:20 +00007297/*
danielk1977e339d652008-06-28 11:23:00 +00007298** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007299**
7300** This routine registers all VFS implementations for unix-like operating
7301** systems. This routine, and the sqlite3_os_end() routine that follows,
7302** should be the only routines in this file that are visible from other
7303** files.
drh6b9d6dd2008-12-03 19:34:47 +00007304**
7305** This routine is called once during SQLite initialization and by a
7306** single thread. The memory allocation and mutex subsystems have not
7307** necessarily been initialized when this routine is called, and so they
7308** should not be used.
drh153c62c2007-08-24 03:51:33 +00007309*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007310int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007311 /*
7312 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007313 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7314 ** to the "finder" function. (pAppData is a pointer to a pointer because
7315 ** silly C90 rules prohibit a void* from being cast to a function pointer
7316 ** and so we have to go through the intermediate pointer to avoid problems
7317 ** when compiling with -pedantic-errors on GCC.)
7318 **
7319 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007320 ** finder-function. The finder-function returns a pointer to the
7321 ** sqlite_io_methods object that implements the desired locking
7322 ** behaviors. See the division above that contains the IOMETHODS
7323 ** macro for addition information on finder-functions.
7324 **
7325 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7326 ** object. But the "autolockIoFinder" available on MacOSX does a little
7327 ** more than that; it looks at the filesystem type that hosts the
7328 ** database file and tries to choose an locking method appropriate for
7329 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007330 */
drh7708e972008-11-29 00:56:52 +00007331 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007332 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007333 sizeof(unixFile), /* szOsFile */ \
7334 MAX_PATHNAME, /* mxPathname */ \
7335 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007336 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007337 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007338 unixOpen, /* xOpen */ \
7339 unixDelete, /* xDelete */ \
7340 unixAccess, /* xAccess */ \
7341 unixFullPathname, /* xFullPathname */ \
7342 unixDlOpen, /* xDlOpen */ \
7343 unixDlError, /* xDlError */ \
7344 unixDlSym, /* xDlSym */ \
7345 unixDlClose, /* xDlClose */ \
7346 unixRandomness, /* xRandomness */ \
7347 unixSleep, /* xSleep */ \
7348 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007349 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007350 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007351 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007352 unixGetSystemCall, /* xGetSystemCall */ \
7353 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007354 }
7355
drh6b9d6dd2008-12-03 19:34:47 +00007356 /*
7357 ** All default VFSes for unix are contained in the following array.
7358 **
7359 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7360 ** by the SQLite core when the VFS is registered. So the following
7361 ** array cannot be const.
7362 */
danielk1977e339d652008-06-28 11:23:00 +00007363 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007364#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007365 UNIXVFS("unix", autolockIoFinder ),
7366#else
7367 UNIXVFS("unix", posixIoFinder ),
7368#endif
7369 UNIXVFS("unix-none", nolockIoFinder ),
7370 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007371 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007372#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007373 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007374#endif
7375#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007376 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007377#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007378 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007379#endif
chw78a13182009-04-07 05:35:03 +00007380#endif
drhd2cb50b2009-01-09 21:41:17 +00007381#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007382 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007383 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007384 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007385#endif
drh153c62c2007-08-24 03:51:33 +00007386 };
drh6b9d6dd2008-12-03 19:34:47 +00007387 unsigned int i; /* Loop counter */
7388
drh2aa5a002011-04-13 13:42:25 +00007389 /* Double-check that the aSyscall[] array has been constructed
7390 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007391 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007392
drh6b9d6dd2008-12-03 19:34:47 +00007393 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007394 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007395 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007396 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007397 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007398}
danielk1977e339d652008-06-28 11:23:00 +00007399
7400/*
drh6b9d6dd2008-12-03 19:34:47 +00007401** Shutdown the operating system interface.
7402**
7403** Some operating systems might need to do some cleanup in this routine,
7404** to release dynamically allocated objects. But not on unix.
7405** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007406*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007407int sqlite3_os_end(void){
7408 return SQLITE_OK;
7409}
drhdce8bdb2007-08-16 13:01:44 +00007410
danielk197729bafea2008-06-26 10:41:19 +00007411#endif /* SQLITE_OS_UNIX */