blob: a97aba87f1ba8f7ebb48bf1143fca8e2e8c0aefe [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
drh6033e152012-11-13 11:08:49 +000049/* Use posix_fallocate() if it is available
50*/
51#if !defined(HAVE_POSIX_FALLOCATE) \
52 && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
53# define HAVE_POSIX_FALLOCATE 1
54#endif
55
danielk1977e339d652008-06-28 11:23:00 +000056/*
drh6b9d6dd2008-12-03 19:34:47 +000057** There are various methods for file locking used for concurrency
58** control:
danielk1977e339d652008-06-28 11:23:00 +000059**
drh734c9862008-11-28 15:37:20 +000060** 1. POSIX locking (the default),
61** 2. No locking,
62** 3. Dot-file locking,
63** 4. flock() locking,
64** 5. AFP locking (OSX only),
65** 6. Named POSIX semaphores (VXWorks only),
66** 7. proxy locking. (OSX only)
67**
68** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
69** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
70** selection of the appropriate locking style based on the filesystem
71** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000072*/
drh40bbb0a2008-09-23 10:23:26 +000073#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000074# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000075# define SQLITE_ENABLE_LOCKING_STYLE 1
76# else
77# define SQLITE_ENABLE_LOCKING_STYLE 0
78# endif
79#endif
drhbfe66312006-10-03 17:40:40 +000080
drh9cbe6352005-11-29 03:13:21 +000081/*
drh6c7d5c52008-11-21 20:32:33 +000082** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000083** vxworks, or 0 otherwise.
84*/
drh6c7d5c52008-11-21 20:32:33 +000085#ifndef OS_VXWORKS
86# if defined(__RTP__) || defined(_WRS_KERNEL)
87# define OS_VXWORKS 1
88# else
89# define OS_VXWORKS 0
90# endif
danielk1977397d65f2008-11-19 11:35:39 +000091#endif
92
93/*
drh9cbe6352005-11-29 03:13:21 +000094** These #defines should enable >2GB file support on Posix if the
95** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000096** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000097**
98** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
99** on the compiler command line. This is necessary if you are compiling
100** on a recent machine (ex: RedHat 7.2) but you want your code to work
101** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
102** without this option, LFS is enable. But LFS does not exist in the kernel
103** in RedHat 6.0, so the code won't work. Hence, for maximum binary
104** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +0000105**
106** The previous paragraph was written in 2005. (This paragraph is written
107** on 2008-11-28.) These days, all Linux kernels support large files, so
108** you should probably leave LFS enabled. But some embedded platforms might
109** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000110*/
111#ifndef SQLITE_DISABLE_LFS
112# define _LARGE_FILE 1
113# ifndef _FILE_OFFSET_BITS
114# define _FILE_OFFSET_BITS 64
115# endif
116# define _LARGEFILE_SOURCE 1
117#endif
drhbbd42a62004-05-22 17:41:58 +0000118
drh9cbe6352005-11-29 03:13:21 +0000119/*
120** standard include files.
121*/
122#include <sys/types.h>
123#include <sys/stat.h>
124#include <fcntl.h>
125#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000126#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000127#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000128#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000129#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000130#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000131#endif
drh1da88f02011-12-17 16:09:16 +0000132
danielk1977e339d652008-06-28 11:23:00 +0000133
drh40bbb0a2008-09-23 10:23:26 +0000134#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000135# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000136# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000137# include <semaphore.h>
138# include <limits.h>
139# else
drh9b35ea62008-11-29 02:20:26 +0000140# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000141# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000142# endif
drhbfe66312006-10-03 17:40:40 +0000143#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000144
drhf8b4d8c2010-03-05 13:53:22 +0000145#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000146# include <sys/mount.h>
147#endif
148
drhdbe4b882011-06-20 18:00:17 +0000149#ifdef HAVE_UTIME
150# include <utime.h>
151#endif
152
drh9cbe6352005-11-29 03:13:21 +0000153/*
drh7ed97b92010-01-20 13:07:21 +0000154** Allowed values of unixFile.fsFlags
155*/
156#define SQLITE_FSFLAGS_IS_MSDOS 0x1
157
158/*
drhf1a221e2006-01-15 17:27:17 +0000159** If we are to be thread-safe, include the pthreads header and define
160** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000161*/
drhd677b3d2007-08-20 22:48:41 +0000162#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000163# include <pthread.h>
164# define SQLITE_UNIX_THREADS 1
165#endif
166
167/*
168** Default permissions when creating a new file
169*/
170#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
171# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
172#endif
173
danielk1977b4b47412007-08-17 15:53:36 +0000174/*
drh5adc60b2012-04-14 13:25:11 +0000175** Default permissions when creating auto proxy dir
176*/
aswiftaebf4132008-11-21 00:10:35 +0000177#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
178# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
179#endif
180
181/*
danielk1977b4b47412007-08-17 15:53:36 +0000182** Maximum supported path-length.
183*/
184#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000185
drh734c9862008-11-28 15:37:20 +0000186/*
drh734c9862008-11-28 15:37:20 +0000187** Only set the lastErrno if the error code is a real error and not
188** a normal expected return code of SQLITE_BUSY or SQLITE_OK
189*/
190#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
191
drhd91c68f2010-05-14 14:52:25 +0000192/* Forward references */
193typedef struct unixShm unixShm; /* Connection shared memory */
194typedef struct unixShmNode unixShmNode; /* Shared memory instance */
195typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
196typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000197
198/*
dane946c392009-08-22 11:39:46 +0000199** Sometimes, after a file handle is closed by SQLite, the file descriptor
200** cannot be closed immediately. In these cases, instances of the following
201** structure are used to store the file descriptor while waiting for an
202** opportunity to either close or reuse it.
203*/
dane946c392009-08-22 11:39:46 +0000204struct UnixUnusedFd {
205 int fd; /* File descriptor to close */
206 int flags; /* Flags this file descriptor was opened with */
207 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
208};
209
210/*
drh9b35ea62008-11-29 02:20:26 +0000211** The unixFile structure is subclass of sqlite3_file specific to the unix
212** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000213*/
drh054889e2005-11-30 03:20:31 +0000214typedef struct unixFile unixFile;
215struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000216 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000217 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000218 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000219 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000220 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000221 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000222 int lastErrno; /* The unix errno from last I/O error */
223 void *lockingContext; /* Locking style specific state */
224 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000225 const char *zPath; /* Name of the file */
226 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000227 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh537dddf2012-10-26 13:46:24 +0000228#ifdef __QNXNTO__
229 int sectorSize; /* Device sector size */
230 int deviceCharacteristics; /* Precomputed device characteristics */
231#endif
drh08c6d442009-02-09 17:34:07 +0000232#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000233 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000234#endif
drh7ed97b92010-01-20 13:07:21 +0000235#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000236 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000237#endif
238#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000239 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000240#endif
drhd3d8c042012-05-29 17:02:40 +0000241#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000242 /* The next group of variables are used to track whether or not the
243 ** transaction counter in bytes 24-27 of database files are updated
244 ** whenever any part of the database changes. An assertion fault will
245 ** occur if a file is updated without also updating the transaction
246 ** counter. This test is made to avoid new problems similar to the
247 ** one described by ticket #3584.
248 */
249 unsigned char transCntrChng; /* True if the transaction counter changed */
250 unsigned char dbUpdate; /* True if any part of database file changed */
251 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000252
drh8f941bc2009-01-14 23:03:40 +0000253#endif
danf23da962013-03-23 21:00:41 +0000254 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
255 sqlite3_int64 mmapOrigsize; /* Actual size of mapping at pMapRegion */
256 sqlite3_int64 mmapLimit; /* Configured FCNTL_MMAP_SIZE value */
257 void *pMapRegion; /* Memory mapped region */
258 int nFetchOut; /* Number of outstanding xFetch refs */
259
danielk1977967a4a12007-08-20 14:23:44 +0000260#ifdef SQLITE_TEST
261 /* In test mode, increase the size of this structure a bit so that
262 ** it is larger than the struct CrashFile defined in test6.c.
263 */
264 char aPadding[32];
265#endif
drh9cbe6352005-11-29 03:13:21 +0000266};
267
drh0ccebe72005-06-07 22:22:50 +0000268/*
drha7e61d82011-03-12 17:02:57 +0000269** Allowed values for the unixFile.ctrlFlags bitmask:
270*/
drhf0b190d2011-07-26 16:03:07 +0000271#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
272#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
273#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000274#ifndef SQLITE_DISABLE_DIRSYNC
275# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
276#else
277# define UNIXFILE_DIRSYNC 0x00
278#endif
drhcb15f352011-12-23 01:04:17 +0000279#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000280#define UNIXFILE_DELETE 0x20 /* Delete on close */
281#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
282#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000283
284/*
drh198bf392006-01-06 21:52:49 +0000285** Include code that is common to all os_*.c files
286*/
287#include "os_common.h"
288
289/*
drh0ccebe72005-06-07 22:22:50 +0000290** Define various macros that are missing from some systems.
291*/
drhbbd42a62004-05-22 17:41:58 +0000292#ifndef O_LARGEFILE
293# define O_LARGEFILE 0
294#endif
295#ifdef SQLITE_DISABLE_LFS
296# undef O_LARGEFILE
297# define O_LARGEFILE 0
298#endif
299#ifndef O_NOFOLLOW
300# define O_NOFOLLOW 0
301#endif
302#ifndef O_BINARY
303# define O_BINARY 0
304#endif
305
306/*
drh2b4b5962005-06-15 17:47:55 +0000307** The threadid macro resolves to the thread-id or to 0. Used for
308** testing and debugging only.
309*/
drhd677b3d2007-08-20 22:48:41 +0000310#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000311#define threadid pthread_self()
312#else
313#define threadid 0
314#endif
315
drh99ab3b12011-03-02 15:09:07 +0000316/*
drh9a3baf12011-04-25 18:01:27 +0000317** Different Unix systems declare open() in different ways. Same use
318** open(const char*,int,mode_t). Others use open(const char*,int,...).
319** The difference is important when using a pointer to the function.
320**
321** The safest way to deal with the problem is to always use this wrapper
322** which always has the same well-defined interface.
323*/
324static int posixOpen(const char *zFile, int flags, int mode){
325 return open(zFile, flags, mode);
326}
327
drhed466822012-05-31 13:10:49 +0000328/*
329** On some systems, calls to fchown() will trigger a message in a security
330** log if they come from non-root processes. So avoid calling fchown() if
331** we are not running as root.
332*/
333static int posixFchown(int fd, uid_t uid, gid_t gid){
334 return geteuid() ? 0 : fchown(fd,uid,gid);
335}
336
drh90315a22011-08-10 01:52:12 +0000337/* Forward reference */
338static int openDirectory(const char*, int*);
339
drh9a3baf12011-04-25 18:01:27 +0000340/*
drh99ab3b12011-03-02 15:09:07 +0000341** Many system calls are accessed through pointer-to-functions so that
342** they may be overridden at runtime to facilitate fault injection during
343** testing and sandboxing. The following array holds the names and pointers
344** to all overrideable system calls.
345*/
346static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000347 const char *zName; /* Name of the sytem call */
348 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
349 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000350} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000351 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
352#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000353
drh58ad5802011-03-23 22:02:23 +0000354 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000355#define osClose ((int(*)(int))aSyscall[1].pCurrent)
356
drh58ad5802011-03-23 22:02:23 +0000357 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000358#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
359
drh58ad5802011-03-23 22:02:23 +0000360 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000361#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
362
drh58ad5802011-03-23 22:02:23 +0000363 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000364#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
365
366/*
367** The DJGPP compiler environment looks mostly like Unix, but it
368** lacks the fcntl() system call. So redefine fcntl() to be something
369** that always succeeds. This means that locking does not occur under
370** DJGPP. But it is DOS - what did you expect?
371*/
372#ifdef __DJGPP__
373 { "fstat", 0, 0 },
374#define osFstat(a,b,c) 0
375#else
drh58ad5802011-03-23 22:02:23 +0000376 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000377#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
378#endif
379
drh58ad5802011-03-23 22:02:23 +0000380 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000381#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
382
drh58ad5802011-03-23 22:02:23 +0000383 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000384#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000385
drh58ad5802011-03-23 22:02:23 +0000386 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000387#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
388
drhd4a80312011-04-15 14:33:20 +0000389#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000390 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000391#else
drh58ad5802011-03-23 22:02:23 +0000392 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000393#endif
394#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
395
396#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000397 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000400#endif
401#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
402
drh58ad5802011-03-23 22:02:23 +0000403 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000404#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
405
drhd4a80312011-04-15 14:33:20 +0000406#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000407 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000408#else
drh58ad5802011-03-23 22:02:23 +0000409 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000410#endif
411#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
412 aSyscall[12].pCurrent)
413
414#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000415 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000416#else
drh58ad5802011-03-23 22:02:23 +0000417 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000418#endif
419#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
420 aSyscall[13].pCurrent)
421
drh58ad5802011-03-23 22:02:23 +0000422 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000423#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000424
425#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000426 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000427#else
drh58ad5802011-03-23 22:02:23 +0000428 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000429#endif
dan0fd7d862011-03-29 10:04:23 +0000430#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000431
drh036ac7f2011-08-08 23:18:05 +0000432 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
433#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
434
drh90315a22011-08-10 01:52:12 +0000435 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
436#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
437
drh9ef6bc42011-11-04 02:24:02 +0000438 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
439#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
440
441 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
442#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
443
drhed466822012-05-31 13:10:49 +0000444 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000445#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000446
drhe562be52011-03-02 18:01:10 +0000447}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000448
449/*
450** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000451** "unix" VFSes. Return SQLITE_OK opon successfully updating the
452** system call pointer, or SQLITE_NOTFOUND if there is no configurable
453** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000454*/
455static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000456 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
457 const char *zName, /* Name of system call to override */
458 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000459){
drh58ad5802011-03-23 22:02:23 +0000460 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000461 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000462
463 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000464 if( zName==0 ){
465 /* If no zName is given, restore all system calls to their default
466 ** settings and return NULL
467 */
dan51438a72011-04-02 17:00:47 +0000468 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000469 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
470 if( aSyscall[i].pDefault ){
471 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000472 }
473 }
474 }else{
475 /* If zName is specified, operate on only the one system call
476 ** specified.
477 */
478 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
479 if( strcmp(zName, aSyscall[i].zName)==0 ){
480 if( aSyscall[i].pDefault==0 ){
481 aSyscall[i].pDefault = aSyscall[i].pCurrent;
482 }
drh1df30962011-03-02 19:06:42 +0000483 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000484 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
485 aSyscall[i].pCurrent = pNewFunc;
486 break;
487 }
488 }
489 }
490 return rc;
491}
492
drh1df30962011-03-02 19:06:42 +0000493/*
494** Return the value of a system call. Return NULL if zName is not a
495** recognized system call name. NULL is also returned if the system call
496** is currently undefined.
497*/
drh58ad5802011-03-23 22:02:23 +0000498static sqlite3_syscall_ptr unixGetSystemCall(
499 sqlite3_vfs *pNotUsed,
500 const char *zName
501){
502 unsigned int i;
503
504 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000505 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
506 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
507 }
508 return 0;
509}
510
511/*
512** Return the name of the first system call after zName. If zName==NULL
513** then return the name of the first system call. Return NULL if zName
514** is the last system call or if zName is not the name of a valid
515** system call.
516*/
517static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000518 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000519
520 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000521 if( zName ){
522 for(i=0; i<ArraySize(aSyscall)-1; i++){
523 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000524 }
525 }
dan0fd7d862011-03-29 10:04:23 +0000526 for(i++; i<ArraySize(aSyscall); i++){
527 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000528 }
529 return 0;
530}
531
drhad4f1e52011-03-04 15:43:57 +0000532/*
drh8c815d12012-02-13 20:16:37 +0000533** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000534** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000535**
536** If the file creation mode "m" is 0 then set it to the default for
537** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
538** 0644) as modified by the system umask. If m is not 0, then
539** make the file creation mode be exactly m ignoring the umask.
540**
541** The m parameter will be non-zero only when creating -wal, -journal,
542** and -shm files. We want those files to have *exactly* the same
543** permissions as their original database, unadulterated by the umask.
544** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
545** transaction crashes and leaves behind hot journals, then any
546** process that is able to write to the database will also be able to
547** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000548*/
drh8c815d12012-02-13 20:16:37 +0000549static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000550 int fd;
drhe1186ab2013-01-04 20:45:13 +0000551 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5adc60b2012-04-14 13:25:11 +0000552 do{
553#if defined(O_CLOEXEC)
554 fd = osOpen(z,f|O_CLOEXEC,m2);
555#else
556 fd = osOpen(z,f,m2);
557#endif
558 }while( fd<0 && errno==EINTR );
drhe1186ab2013-01-04 20:45:13 +0000559 if( fd>=0 ){
560 if( m!=0 ){
561 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000562 if( osFstat(fd, &statbuf)==0
563 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000564 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000565 ){
drhe1186ab2013-01-04 20:45:13 +0000566 osFchmod(fd, m);
567 }
568 }
drh5adc60b2012-04-14 13:25:11 +0000569#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000570 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000571#endif
drhe1186ab2013-01-04 20:45:13 +0000572 }
drh5adc60b2012-04-14 13:25:11 +0000573 return fd;
drhad4f1e52011-03-04 15:43:57 +0000574}
danielk197713adf8a2004-06-03 16:08:41 +0000575
drh107886a2008-11-21 22:21:50 +0000576/*
dan9359c7b2009-08-21 08:29:10 +0000577** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000578** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000579** vxworksFileId objects used by this file, all of which may be
580** shared by multiple threads.
581**
582** Function unixMutexHeld() is used to assert() that the global mutex
583** is held when required. This function is only used as part of assert()
584** statements. e.g.
585**
586** unixEnterMutex()
587** assert( unixMutexHeld() );
588** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000589*/
590static void unixEnterMutex(void){
591 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
592}
593static void unixLeaveMutex(void){
594 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
595}
dan9359c7b2009-08-21 08:29:10 +0000596#ifdef SQLITE_DEBUG
597static int unixMutexHeld(void) {
598 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
599}
600#endif
drh107886a2008-11-21 22:21:50 +0000601
drh734c9862008-11-28 15:37:20 +0000602
drh30ddce62011-10-15 00:16:30 +0000603#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000604/*
605** Helper function for printing out trace information from debugging
606** binaries. This returns the string represetation of the supplied
607** integer lock-type.
608*/
drh308c2a52010-05-14 11:30:18 +0000609static const char *azFileLock(int eFileLock){
610 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000611 case NO_LOCK: return "NONE";
612 case SHARED_LOCK: return "SHARED";
613 case RESERVED_LOCK: return "RESERVED";
614 case PENDING_LOCK: return "PENDING";
615 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000616 }
617 return "ERROR";
618}
619#endif
620
621#ifdef SQLITE_LOCK_TRACE
622/*
623** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000624**
drh734c9862008-11-28 15:37:20 +0000625** This routine is used for troubleshooting locks on multithreaded
626** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
627** command-line option on the compiler. This code is normally
628** turned off.
629*/
630static int lockTrace(int fd, int op, struct flock *p){
631 char *zOpName, *zType;
632 int s;
633 int savedErrno;
634 if( op==F_GETLK ){
635 zOpName = "GETLK";
636 }else if( op==F_SETLK ){
637 zOpName = "SETLK";
638 }else{
drh99ab3b12011-03-02 15:09:07 +0000639 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000640 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
641 return s;
642 }
643 if( p->l_type==F_RDLCK ){
644 zType = "RDLCK";
645 }else if( p->l_type==F_WRLCK ){
646 zType = "WRLCK";
647 }else if( p->l_type==F_UNLCK ){
648 zType = "UNLCK";
649 }else{
650 assert( 0 );
651 }
652 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000653 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000654 savedErrno = errno;
655 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
656 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
657 (int)p->l_pid, s);
658 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
659 struct flock l2;
660 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000661 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000662 if( l2.l_type==F_RDLCK ){
663 zType = "RDLCK";
664 }else if( l2.l_type==F_WRLCK ){
665 zType = "WRLCK";
666 }else if( l2.l_type==F_UNLCK ){
667 zType = "UNLCK";
668 }else{
669 assert( 0 );
670 }
671 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
672 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
673 }
674 errno = savedErrno;
675 return s;
676}
drh99ab3b12011-03-02 15:09:07 +0000677#undef osFcntl
678#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000679#endif /* SQLITE_LOCK_TRACE */
680
drhff812312011-02-23 13:33:46 +0000681/*
682** Retry ftruncate() calls that fail due to EINTR
683*/
drhff812312011-02-23 13:33:46 +0000684static int robust_ftruncate(int h, sqlite3_int64 sz){
685 int rc;
drh99ab3b12011-03-02 15:09:07 +0000686 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000687 return rc;
688}
drh734c9862008-11-28 15:37:20 +0000689
690/*
691** This routine translates a standard POSIX errno code into something
692** useful to the clients of the sqlite3 functions. Specifically, it is
693** intended to translate a variety of "try again" errors into SQLITE_BUSY
694** and a variety of "please close the file descriptor NOW" errors into
695** SQLITE_IOERR
696**
697** Errors during initialization of locks, or file system support for locks,
698** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
699*/
700static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
701 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000702#if 0
703 /* At one point this code was not commented out. In theory, this branch
704 ** should never be hit, as this function should only be called after
705 ** a locking-related function (i.e. fcntl()) has returned non-zero with
706 ** the value of errno as the first argument. Since a system call has failed,
707 ** errno should be non-zero.
708 **
709 ** Despite this, if errno really is zero, we still don't want to return
710 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
711 ** propagated back to the caller. Commenting this branch out means errno==0
712 ** will be handled by the "default:" case below.
713 */
drh734c9862008-11-28 15:37:20 +0000714 case 0:
715 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000716#endif
717
drh734c9862008-11-28 15:37:20 +0000718 case EAGAIN:
719 case ETIMEDOUT:
720 case EBUSY:
721 case EINTR:
722 case ENOLCK:
723 /* random NFS retry error, unless during file system support
724 * introspection, in which it actually means what it says */
725 return SQLITE_BUSY;
726
727 case EACCES:
728 /* EACCES is like EAGAIN during locking operations, but not any other time*/
729 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000730 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
731 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
732 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000733 return SQLITE_BUSY;
734 }
735 /* else fall through */
736 case EPERM:
737 return SQLITE_PERM;
738
danea83bc62011-04-01 11:56:32 +0000739 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
740 ** this module never makes such a call. And the code in SQLite itself
741 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
742 ** this case is also commented out. If the system does set errno to EDEADLK,
743 ** the default SQLITE_IOERR_XXX code will be returned. */
744#if 0
drh734c9862008-11-28 15:37:20 +0000745 case EDEADLK:
746 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000747#endif
drh734c9862008-11-28 15:37:20 +0000748
749#if EOPNOTSUPP!=ENOTSUP
750 case EOPNOTSUPP:
751 /* something went terribly awry, unless during file system support
752 * introspection, in which it actually means what it says */
753#endif
754#ifdef ENOTSUP
755 case ENOTSUP:
756 /* invalid fd, unless during file system support introspection, in which
757 * it actually means what it says */
758#endif
759 case EIO:
760 case EBADF:
761 case EINVAL:
762 case ENOTCONN:
763 case ENODEV:
764 case ENXIO:
765 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000766#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000767 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000768#endif
drh734c9862008-11-28 15:37:20 +0000769 case ENOSYS:
770 /* these should force the client to close the file and reconnect */
771
772 default:
773 return sqliteIOErr;
774 }
775}
776
777
778
779/******************************************************************************
780****************** Begin Unique File ID Utility Used By VxWorks ***************
781**
782** On most versions of unix, we can get a unique ID for a file by concatenating
783** the device number and the inode number. But this does not work on VxWorks.
784** On VxWorks, a unique file id must be based on the canonical filename.
785**
786** A pointer to an instance of the following structure can be used as a
787** unique file ID in VxWorks. Each instance of this structure contains
788** a copy of the canonical filename. There is also a reference count.
789** The structure is reclaimed when the number of pointers to it drops to
790** zero.
791**
792** There are never very many files open at one time and lookups are not
793** a performance-critical path, so it is sufficient to put these
794** structures on a linked list.
795*/
796struct vxworksFileId {
797 struct vxworksFileId *pNext; /* Next in a list of them all */
798 int nRef; /* Number of references to this one */
799 int nName; /* Length of the zCanonicalName[] string */
800 char *zCanonicalName; /* Canonical filename */
801};
802
803#if OS_VXWORKS
804/*
drh9b35ea62008-11-29 02:20:26 +0000805** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000806** variable:
807*/
808static struct vxworksFileId *vxworksFileList = 0;
809
810/*
811** Simplify a filename into its canonical form
812** by making the following changes:
813**
814** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000815** * convert /./ into just /
816** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000817**
818** Changes are made in-place. Return the new name length.
819**
820** The original filename is in z[0..n-1]. Return the number of
821** characters in the simplified name.
822*/
823static int vxworksSimplifyName(char *z, int n){
824 int i, j;
825 while( n>1 && z[n-1]=='/' ){ n--; }
826 for(i=j=0; i<n; i++){
827 if( z[i]=='/' ){
828 if( z[i+1]=='/' ) continue;
829 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
830 i += 1;
831 continue;
832 }
833 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
834 while( j>0 && z[j-1]!='/' ){ j--; }
835 if( j>0 ){ j--; }
836 i += 2;
837 continue;
838 }
839 }
840 z[j++] = z[i];
841 }
842 z[j] = 0;
843 return j;
844}
845
846/*
847** Find a unique file ID for the given absolute pathname. Return
848** a pointer to the vxworksFileId object. This pointer is the unique
849** file ID.
850**
851** The nRef field of the vxworksFileId object is incremented before
852** the object is returned. A new vxworksFileId object is created
853** and added to the global list if necessary.
854**
855** If a memory allocation error occurs, return NULL.
856*/
857static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
858 struct vxworksFileId *pNew; /* search key and new file ID */
859 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
860 int n; /* Length of zAbsoluteName string */
861
862 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000863 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000864 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
865 if( pNew==0 ) return 0;
866 pNew->zCanonicalName = (char*)&pNew[1];
867 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
868 n = vxworksSimplifyName(pNew->zCanonicalName, n);
869
870 /* Search for an existing entry that matching the canonical name.
871 ** If found, increment the reference count and return a pointer to
872 ** the existing file ID.
873 */
874 unixEnterMutex();
875 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
876 if( pCandidate->nName==n
877 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
878 ){
879 sqlite3_free(pNew);
880 pCandidate->nRef++;
881 unixLeaveMutex();
882 return pCandidate;
883 }
884 }
885
886 /* No match was found. We will make a new file ID */
887 pNew->nRef = 1;
888 pNew->nName = n;
889 pNew->pNext = vxworksFileList;
890 vxworksFileList = pNew;
891 unixLeaveMutex();
892 return pNew;
893}
894
895/*
896** Decrement the reference count on a vxworksFileId object. Free
897** the object when the reference count reaches zero.
898*/
899static void vxworksReleaseFileId(struct vxworksFileId *pId){
900 unixEnterMutex();
901 assert( pId->nRef>0 );
902 pId->nRef--;
903 if( pId->nRef==0 ){
904 struct vxworksFileId **pp;
905 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
906 assert( *pp==pId );
907 *pp = pId->pNext;
908 sqlite3_free(pId);
909 }
910 unixLeaveMutex();
911}
912#endif /* OS_VXWORKS */
913/*************** End of Unique File ID Utility Used By VxWorks ****************
914******************************************************************************/
915
916
917/******************************************************************************
918*************************** Posix Advisory Locking ****************************
919**
drh9b35ea62008-11-29 02:20:26 +0000920** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000921** section 6.5.2.2 lines 483 through 490 specify that when a process
922** sets or clears a lock, that operation overrides any prior locks set
923** by the same process. It does not explicitly say so, but this implies
924** that it overrides locks set by the same process using a different
925** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000926**
927** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000928** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
929**
930** Suppose ./file1 and ./file2 are really the same file (because
931** one is a hard or symbolic link to the other) then if you set
932** an exclusive lock on fd1, then try to get an exclusive lock
933** on fd2, it works. I would have expected the second lock to
934** fail since there was already a lock on the file due to fd1.
935** But not so. Since both locks came from the same process, the
936** second overrides the first, even though they were on different
937** file descriptors opened on different file names.
938**
drh734c9862008-11-28 15:37:20 +0000939** This means that we cannot use POSIX locks to synchronize file access
940** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000941** to synchronize access for threads in separate processes, but not
942** threads within the same process.
943**
944** To work around the problem, SQLite has to manage file locks internally
945** on its own. Whenever a new database is opened, we have to find the
946** specific inode of the database file (the inode is determined by the
947** st_dev and st_ino fields of the stat structure that fstat() fills in)
948** and check for locks already existing on that inode. When locks are
949** created or removed, we have to look at our own internal record of the
950** locks to see if another thread has previously set a lock on that same
951** inode.
952**
drh9b35ea62008-11-29 02:20:26 +0000953** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
954** For VxWorks, we have to use the alternative unique ID system based on
955** canonical filename and implemented in the previous division.)
956**
danielk1977ad94b582007-08-20 06:44:22 +0000957** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000958** descriptor. It is now a structure that holds the integer file
959** descriptor and a pointer to a structure that describes the internal
960** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000961** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000962** point to the same locking structure. The locking structure keeps
963** a reference count (so we will know when to delete it) and a "cnt"
964** field that tells us its internal lock status. cnt==0 means the
965** file is unlocked. cnt==-1 means the file has an exclusive lock.
966** cnt>0 means there are cnt shared locks on the file.
967**
968** Any attempt to lock or unlock a file first checks the locking
969** structure. The fcntl() system call is only invoked to set a
970** POSIX lock if the internal lock structure transitions between
971** a locked and an unlocked state.
972**
drh734c9862008-11-28 15:37:20 +0000973** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000974**
975** If you close a file descriptor that points to a file that has locks,
976** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000977** released. To work around this problem, each unixInodeInfo object
978** maintains a count of the number of pending locks on tha inode.
979** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000980** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000981** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000982** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000983** be closed and that list is walked (and cleared) when the last lock
984** clears.
985**
drh9b35ea62008-11-29 02:20:26 +0000986** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000987**
drh9b35ea62008-11-29 02:20:26 +0000988** Many older versions of linux use the LinuxThreads library which is
989** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000990** A cannot be modified or overridden by a different thread B.
991** Only thread A can modify the lock. Locking behavior is correct
992** if the appliation uses the newer Native Posix Thread Library (NPTL)
993** on linux - with NPTL a lock created by thread A can override locks
994** in thread B. But there is no way to know at compile-time which
995** threading library is being used. So there is no way to know at
996** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000997** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000998** current process.
drh5fdae772004-06-29 03:29:00 +0000999**
drh8af6c222010-05-14 12:43:01 +00001000** SQLite used to support LinuxThreads. But support for LinuxThreads
1001** was dropped beginning with version 3.7.0. SQLite will still work with
1002** LinuxThreads provided that (1) there is no more than one connection
1003** per database file in the same process and (2) database connections
1004** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001005*/
1006
1007/*
1008** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001009** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001010*/
1011struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001012 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001013#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001014 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001015#else
drh107886a2008-11-21 22:21:50 +00001016 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001017#endif
1018};
1019
1020/*
drhbbd42a62004-05-22 17:41:58 +00001021** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001022** inode. Or, on LinuxThreads, there is one of these structures for
1023** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001024**
danielk1977ad94b582007-08-20 06:44:22 +00001025** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001026** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001027** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001028*/
drh8af6c222010-05-14 12:43:01 +00001029struct unixInodeInfo {
1030 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001031 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001032 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1033 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001034 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001035 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1036 int nLock; /* Number of outstanding file locks */
1037 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1038 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1039 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001040#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001041 unsigned long long sharedByte; /* for AFP simulated shared lock */
1042#endif
drh6c7d5c52008-11-21 20:32:33 +00001043#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001044 sem_t *pSem; /* Named POSIX semaphore */
1045 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001046#endif
drhbbd42a62004-05-22 17:41:58 +00001047};
1048
drhda0e7682008-07-30 15:27:54 +00001049/*
drh8af6c222010-05-14 12:43:01 +00001050** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001051*/
drhd91c68f2010-05-14 14:52:25 +00001052static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001053
drh5fdae772004-06-29 03:29:00 +00001054/*
dane18d4952011-02-21 11:46:24 +00001055**
1056** This function - unixLogError_x(), is only ever called via the macro
1057** unixLogError().
1058**
1059** It is invoked after an error occurs in an OS function and errno has been
1060** set. It logs a message using sqlite3_log() containing the current value of
1061** errno and, if possible, the human-readable equivalent from strerror() or
1062** strerror_r().
1063**
1064** The first argument passed to the macro should be the error code that
1065** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1066** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001067** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001068** if any.
1069*/
drh0e9365c2011-03-02 02:08:13 +00001070#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1071static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001072 int errcode, /* SQLite error code */
1073 const char *zFunc, /* Name of OS function that failed */
1074 const char *zPath, /* File path associated with error */
1075 int iLine /* Source line number where error occurred */
1076){
1077 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001078 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001079
1080 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1081 ** the strerror() function to obtain the human-readable error message
1082 ** equivalent to errno. Otherwise, use strerror_r().
1083 */
1084#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1085 char aErr[80];
1086 memset(aErr, 0, sizeof(aErr));
1087 zErr = aErr;
1088
1089 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001090 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001091 ** returns a pointer to a buffer containing the error message. That pointer
1092 ** may point to aErr[], or it may point to some static storage somewhere.
1093 ** Otherwise, assume that the system provides the POSIX version of
1094 ** strerror_r(), which always writes an error message into aErr[].
1095 **
1096 ** If the code incorrectly assumes that it is the POSIX version that is
1097 ** available, the error message will often be an empty string. Not a
1098 ** huge problem. Incorrectly concluding that the GNU version is available
1099 ** could lead to a segfault though.
1100 */
1101#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1102 zErr =
1103# endif
drh0e9365c2011-03-02 02:08:13 +00001104 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001105
1106#elif SQLITE_THREADSAFE
1107 /* This is a threadsafe build, but strerror_r() is not available. */
1108 zErr = "";
1109#else
1110 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001111 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001112#endif
1113
1114 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001115 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001116 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001117 "os_unix.c:%d: (%d) %s(%s) - %s",
1118 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001119 );
1120
1121 return errcode;
1122}
1123
drh0e9365c2011-03-02 02:08:13 +00001124/*
1125** Close a file descriptor.
1126**
1127** We assume that close() almost always works, since it is only in a
1128** very sick application or on a very sick platform that it might fail.
1129** If it does fail, simply leak the file descriptor, but do log the
1130** error.
1131**
1132** Note that it is not safe to retry close() after EINTR since the
1133** file descriptor might have already been reused by another thread.
1134** So we don't even try to recover from an EINTR. Just log the error
1135** and move on.
1136*/
1137static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001138 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001139 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1140 pFile ? pFile->zPath : 0, lineno);
1141 }
1142}
dane18d4952011-02-21 11:46:24 +00001143
1144/*
danb0ac3e32010-06-16 10:55:42 +00001145** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001146*/
drh0e9365c2011-03-02 02:08:13 +00001147static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001148 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001149 UnixUnusedFd *p;
1150 UnixUnusedFd *pNext;
1151 for(p=pInode->pUnused; p; p=pNext){
1152 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001153 robust_close(pFile, p->fd, __LINE__);
1154 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001155 }
drh0e9365c2011-03-02 02:08:13 +00001156 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001157}
1158
1159/*
drh8af6c222010-05-14 12:43:01 +00001160** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001161**
1162** The mutex entered using the unixEnterMutex() function must be held
1163** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001164*/
danb0ac3e32010-06-16 10:55:42 +00001165static void releaseInodeInfo(unixFile *pFile){
1166 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001167 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001168 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001169 pInode->nRef--;
1170 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001171 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001172 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001173 if( pInode->pPrev ){
1174 assert( pInode->pPrev->pNext==pInode );
1175 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001176 }else{
drh8af6c222010-05-14 12:43:01 +00001177 assert( inodeList==pInode );
1178 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001179 }
drh8af6c222010-05-14 12:43:01 +00001180 if( pInode->pNext ){
1181 assert( pInode->pNext->pPrev==pInode );
1182 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001183 }
drh8af6c222010-05-14 12:43:01 +00001184 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001185 }
drhbbd42a62004-05-22 17:41:58 +00001186 }
1187}
1188
1189/*
drh8af6c222010-05-14 12:43:01 +00001190** Given a file descriptor, locate the unixInodeInfo object that
1191** describes that file descriptor. Create a new one if necessary. The
1192** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001193**
dan9359c7b2009-08-21 08:29:10 +00001194** The mutex entered using the unixEnterMutex() function must be held
1195** when this function is called.
1196**
drh6c7d5c52008-11-21 20:32:33 +00001197** Return an appropriate error code.
1198*/
drh8af6c222010-05-14 12:43:01 +00001199static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001200 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001201 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001202){
1203 int rc; /* System call return code */
1204 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001205 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1206 struct stat statbuf; /* Low-level file information */
1207 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001208
dan9359c7b2009-08-21 08:29:10 +00001209 assert( unixMutexHeld() );
1210
drh6c7d5c52008-11-21 20:32:33 +00001211 /* Get low-level information about the file that we can used to
1212 ** create a unique name for the file.
1213 */
1214 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001215 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001216 if( rc!=0 ){
1217 pFile->lastErrno = errno;
1218#ifdef EOVERFLOW
1219 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1220#endif
1221 return SQLITE_IOERR;
1222 }
1223
drheb0d74f2009-02-03 15:27:02 +00001224#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001225 /* On OS X on an msdos filesystem, the inode number is reported
1226 ** incorrectly for zero-size files. See ticket #3260. To work
1227 ** around this problem (we consider it a bug in OS X, not SQLite)
1228 ** we always increase the file size to 1 by writing a single byte
1229 ** prior to accessing the inode number. The one byte written is
1230 ** an ASCII 'S' character which also happens to be the first byte
1231 ** in the header of every SQLite database. In this way, if there
1232 ** is a race condition such that another thread has already populated
1233 ** the first page of the database, no damage is done.
1234 */
drh7ed97b92010-01-20 13:07:21 +00001235 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001236 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001237 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001238 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001239 return SQLITE_IOERR;
1240 }
drh99ab3b12011-03-02 15:09:07 +00001241 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001242 if( rc!=0 ){
1243 pFile->lastErrno = errno;
1244 return SQLITE_IOERR;
1245 }
1246 }
drheb0d74f2009-02-03 15:27:02 +00001247#endif
drh6c7d5c52008-11-21 20:32:33 +00001248
drh8af6c222010-05-14 12:43:01 +00001249 memset(&fileId, 0, sizeof(fileId));
1250 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001251#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001252 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001253#else
drh8af6c222010-05-14 12:43:01 +00001254 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001255#endif
drh8af6c222010-05-14 12:43:01 +00001256 pInode = inodeList;
1257 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1258 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001259 }
drh8af6c222010-05-14 12:43:01 +00001260 if( pInode==0 ){
1261 pInode = sqlite3_malloc( sizeof(*pInode) );
1262 if( pInode==0 ){
1263 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001264 }
drh8af6c222010-05-14 12:43:01 +00001265 memset(pInode, 0, sizeof(*pInode));
1266 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1267 pInode->nRef = 1;
1268 pInode->pNext = inodeList;
1269 pInode->pPrev = 0;
1270 if( inodeList ) inodeList->pPrev = pInode;
1271 inodeList = pInode;
1272 }else{
1273 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001274 }
drh8af6c222010-05-14 12:43:01 +00001275 *ppInode = pInode;
1276 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001277}
drh6c7d5c52008-11-21 20:32:33 +00001278
aswift5b1a2562008-08-22 00:22:35 +00001279
1280/*
danielk197713adf8a2004-06-03 16:08:41 +00001281** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001282** file by this or any other process. If such a lock is held, set *pResOut
1283** to a non-zero value otherwise *pResOut is set to zero. The return value
1284** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001285*/
danielk1977861f7452008-06-05 11:39:11 +00001286static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001287 int rc = SQLITE_OK;
1288 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001289 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001290
danielk1977861f7452008-06-05 11:39:11 +00001291 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1292
drh054889e2005-11-30 03:20:31 +00001293 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001294 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001295
1296 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001297 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001298 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001299 }
1300
drh2ac3ee92004-06-07 16:27:46 +00001301 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001302 */
danielk197709480a92009-02-09 05:32:32 +00001303#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001304 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001305 struct flock lock;
1306 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001307 lock.l_start = RESERVED_BYTE;
1308 lock.l_len = 1;
1309 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001310 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1311 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1312 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001313 } else if( lock.l_type!=F_UNLCK ){
1314 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001315 }
1316 }
danielk197709480a92009-02-09 05:32:32 +00001317#endif
danielk197713adf8a2004-06-03 16:08:41 +00001318
drh6c7d5c52008-11-21 20:32:33 +00001319 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001320 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001321
aswift5b1a2562008-08-22 00:22:35 +00001322 *pResOut = reserved;
1323 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001324}
1325
1326/*
drha7e61d82011-03-12 17:02:57 +00001327** Attempt to set a system-lock on the file pFile. The lock is
1328** described by pLock.
1329**
drh77197112011-03-15 19:08:48 +00001330** If the pFile was opened read/write from unix-excl, then the only lock
1331** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001332** the first time any lock is attempted. All subsequent system locking
1333** operations become no-ops. Locking operations still happen internally,
1334** in order to coordinate access between separate database connections
1335** within this process, but all of that is handled in memory and the
1336** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001337**
1338** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1339** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1340** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001341**
1342** Zero is returned if the call completes successfully, or -1 if a call
1343** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001344*/
1345static int unixFileLock(unixFile *pFile, struct flock *pLock){
1346 int rc;
drh3cb93392011-03-12 18:10:44 +00001347 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001348 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001349 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001350 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1351 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1352 ){
drh3cb93392011-03-12 18:10:44 +00001353 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001354 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001355 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001356 lock.l_whence = SEEK_SET;
1357 lock.l_start = SHARED_FIRST;
1358 lock.l_len = SHARED_SIZE;
1359 lock.l_type = F_WRLCK;
1360 rc = osFcntl(pFile->h, F_SETLK, &lock);
1361 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001362 pInode->bProcessLock = 1;
1363 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001364 }else{
1365 rc = 0;
1366 }
1367 }else{
1368 rc = osFcntl(pFile->h, F_SETLK, pLock);
1369 }
1370 return rc;
1371}
1372
1373/*
drh308c2a52010-05-14 11:30:18 +00001374** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001375** of the following:
1376**
drh2ac3ee92004-06-07 16:27:46 +00001377** (1) SHARED_LOCK
1378** (2) RESERVED_LOCK
1379** (3) PENDING_LOCK
1380** (4) EXCLUSIVE_LOCK
1381**
drhb3e04342004-06-08 00:47:47 +00001382** Sometimes when requesting one lock state, additional lock states
1383** are inserted in between. The locking might fail on one of the later
1384** transitions leaving the lock state different from what it started but
1385** still short of its goal. The following chart shows the allowed
1386** transitions and the inserted intermediate states:
1387**
1388** UNLOCKED -> SHARED
1389** SHARED -> RESERVED
1390** SHARED -> (PENDING) -> EXCLUSIVE
1391** RESERVED -> (PENDING) -> EXCLUSIVE
1392** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001393**
drha6abd042004-06-09 17:37:22 +00001394** This routine will only increase a lock. Use the sqlite3OsUnlock()
1395** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001396*/
drh308c2a52010-05-14 11:30:18 +00001397static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001398 /* The following describes the implementation of the various locks and
1399 ** lock transitions in terms of the POSIX advisory shared and exclusive
1400 ** lock primitives (called read-locks and write-locks below, to avoid
1401 ** confusion with SQLite lock names). The algorithms are complicated
1402 ** slightly in order to be compatible with windows systems simultaneously
1403 ** accessing the same database file, in case that is ever required.
1404 **
1405 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1406 ** byte', each single bytes at well known offsets, and the 'shared byte
1407 ** range', a range of 510 bytes at a well known offset.
1408 **
1409 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1410 ** byte'. If this is successful, a random byte from the 'shared byte
1411 ** range' is read-locked and the lock on the 'pending byte' released.
1412 **
danielk197790ba3bd2004-06-25 08:32:25 +00001413 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1414 ** A RESERVED lock is implemented by grabbing a write-lock on the
1415 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001416 **
1417 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001418 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1419 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1420 ** obtained, but existing SHARED locks are allowed to persist. A process
1421 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1422 ** This property is used by the algorithm for rolling back a journal file
1423 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001424 **
danielk197790ba3bd2004-06-25 08:32:25 +00001425 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1426 ** implemented by obtaining a write-lock on the entire 'shared byte
1427 ** range'. Since all other locks require a read-lock on one of the bytes
1428 ** within this range, this ensures that no other locks are held on the
1429 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001430 **
1431 ** The reason a single byte cannot be used instead of the 'shared byte
1432 ** range' is that some versions of windows do not support read-locks. By
1433 ** locking a random byte from a range, concurrent SHARED locks may exist
1434 ** even if the locking primitive used is always a write-lock.
1435 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001436 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001437 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001438 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001439 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001440 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001441
drh054889e2005-11-30 03:20:31 +00001442 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001443 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1444 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001445 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001446
1447 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001448 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001449 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001450 */
drh308c2a52010-05-14 11:30:18 +00001451 if( pFile->eFileLock>=eFileLock ){
1452 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1453 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001454 return SQLITE_OK;
1455 }
1456
drh0c2694b2009-09-03 16:23:44 +00001457 /* Make sure the locking sequence is correct.
1458 ** (1) We never move from unlocked to anything higher than shared lock.
1459 ** (2) SQLite never explicitly requests a pendig lock.
1460 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001461 */
drh308c2a52010-05-14 11:30:18 +00001462 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1463 assert( eFileLock!=PENDING_LOCK );
1464 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001465
drh8af6c222010-05-14 12:43:01 +00001466 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001467 */
drh6c7d5c52008-11-21 20:32:33 +00001468 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001469 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001470
danielk1977ad94b582007-08-20 06:44:22 +00001471 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001472 ** handle that precludes the requested lock, return BUSY.
1473 */
drh8af6c222010-05-14 12:43:01 +00001474 if( (pFile->eFileLock!=pInode->eFileLock &&
1475 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001476 ){
1477 rc = SQLITE_BUSY;
1478 goto end_lock;
1479 }
1480
1481 /* If a SHARED lock is requested, and some thread using this PID already
1482 ** has a SHARED or RESERVED lock, then increment reference counts and
1483 ** return SQLITE_OK.
1484 */
drh308c2a52010-05-14 11:30:18 +00001485 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001486 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001487 assert( eFileLock==SHARED_LOCK );
1488 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001489 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001490 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001491 pInode->nShared++;
1492 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001493 goto end_lock;
1494 }
1495
danielk19779a1d0ab2004-06-01 14:09:28 +00001496
drh3cde3bb2004-06-12 02:17:14 +00001497 /* A PENDING lock is needed before acquiring a SHARED lock and before
1498 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1499 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001500 */
drh0c2694b2009-09-03 16:23:44 +00001501 lock.l_len = 1L;
1502 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001503 if( eFileLock==SHARED_LOCK
1504 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001505 ){
drh308c2a52010-05-14 11:30:18 +00001506 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001507 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001508 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001509 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001510 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001511 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001512 pFile->lastErrno = tErrno;
1513 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001514 goto end_lock;
1515 }
drh3cde3bb2004-06-12 02:17:14 +00001516 }
1517
1518
1519 /* If control gets to this point, then actually go ahead and make
1520 ** operating system calls for the specified lock.
1521 */
drh308c2a52010-05-14 11:30:18 +00001522 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001523 assert( pInode->nShared==0 );
1524 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001525 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001526
drh2ac3ee92004-06-07 16:27:46 +00001527 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001528 lock.l_start = SHARED_FIRST;
1529 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001530 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001531 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001532 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001533 }
dan661d71a2011-03-30 19:08:03 +00001534
drh2ac3ee92004-06-07 16:27:46 +00001535 /* Drop the temporary PENDING lock */
1536 lock.l_start = PENDING_BYTE;
1537 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001538 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001539 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1540 /* This could happen with a network mount */
1541 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001542 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001543 }
dan661d71a2011-03-30 19:08:03 +00001544
1545 if( rc ){
1546 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001547 pFile->lastErrno = tErrno;
1548 }
dan661d71a2011-03-30 19:08:03 +00001549 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001550 }else{
drh308c2a52010-05-14 11:30:18 +00001551 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001552 pInode->nLock++;
1553 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001554 }
drh8af6c222010-05-14 12:43:01 +00001555 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001556 /* We are trying for an exclusive lock but another thread in this
1557 ** same process is still holding a shared lock. */
1558 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001559 }else{
drh3cde3bb2004-06-12 02:17:14 +00001560 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001561 ** assumed that there is a SHARED or greater lock on the file
1562 ** already.
1563 */
drh308c2a52010-05-14 11:30:18 +00001564 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001565 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001566
1567 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1568 if( eFileLock==RESERVED_LOCK ){
1569 lock.l_start = RESERVED_BYTE;
1570 lock.l_len = 1L;
1571 }else{
1572 lock.l_start = SHARED_FIRST;
1573 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001574 }
dan661d71a2011-03-30 19:08:03 +00001575
1576 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001577 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001578 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001579 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001580 pFile->lastErrno = tErrno;
1581 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001582 }
drhbbd42a62004-05-22 17:41:58 +00001583 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001584
drh8f941bc2009-01-14 23:03:40 +00001585
drhd3d8c042012-05-29 17:02:40 +00001586#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001587 /* Set up the transaction-counter change checking flags when
1588 ** transitioning from a SHARED to a RESERVED lock. The change
1589 ** from SHARED to RESERVED marks the beginning of a normal
1590 ** write operation (not a hot journal rollback).
1591 */
1592 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001593 && pFile->eFileLock<=SHARED_LOCK
1594 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001595 ){
1596 pFile->transCntrChng = 0;
1597 pFile->dbUpdate = 0;
1598 pFile->inNormalWrite = 1;
1599 }
1600#endif
1601
1602
danielk1977ecb2a962004-06-02 06:30:16 +00001603 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001604 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001605 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001606 }else if( eFileLock==EXCLUSIVE_LOCK ){
1607 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001608 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001609 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001610
1611end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001612 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001613 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1614 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001615 return rc;
1616}
1617
1618/*
dan08da86a2009-08-21 17:18:03 +00001619** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001620** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001621*/
1622static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001623 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001624 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001625 p->pNext = pInode->pUnused;
1626 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001627 pFile->h = -1;
1628 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001629}
1630
1631/*
drh308c2a52010-05-14 11:30:18 +00001632** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001633** must be either NO_LOCK or SHARED_LOCK.
1634**
1635** If the locking level of the file descriptor is already at or below
1636** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001637**
1638** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1639** the byte range is divided into 2 parts and the first part is unlocked then
1640** set to a read lock, then the other part is simply unlocked. This works
1641** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1642** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001643*/
drha7e61d82011-03-12 17:02:57 +00001644static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001645 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001646 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001647 struct flock lock;
1648 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001649
drh054889e2005-11-30 03:20:31 +00001650 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001651 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001652 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001653 getpid()));
drha6abd042004-06-09 17:37:22 +00001654
drh308c2a52010-05-14 11:30:18 +00001655 assert( eFileLock<=SHARED_LOCK );
1656 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001657 return SQLITE_OK;
1658 }
drh6c7d5c52008-11-21 20:32:33 +00001659 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001660 pInode = pFile->pInode;
1661 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001662 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001663 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001664
drhd3d8c042012-05-29 17:02:40 +00001665#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001666 /* When reducing a lock such that other processes can start
1667 ** reading the database file again, make sure that the
1668 ** transaction counter was updated if any part of the database
1669 ** file changed. If the transaction counter is not updated,
1670 ** other connections to the same file might not realize that
1671 ** the file has changed and hence might not know to flush their
1672 ** cache. The use of a stale cache can lead to database corruption.
1673 */
drh8f941bc2009-01-14 23:03:40 +00001674 pFile->inNormalWrite = 0;
1675#endif
1676
drh7ed97b92010-01-20 13:07:21 +00001677 /* downgrading to a shared lock on NFS involves clearing the write lock
1678 ** before establishing the readlock - to avoid a race condition we downgrade
1679 ** the lock in 2 blocks, so that part of the range will be covered by a
1680 ** write lock until the rest is covered by a read lock:
1681 ** 1: [WWWWW]
1682 ** 2: [....W]
1683 ** 3: [RRRRW]
1684 ** 4: [RRRR.]
1685 */
drh308c2a52010-05-14 11:30:18 +00001686 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001687
1688#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001689 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001690 assert( handleNFSUnlock==0 );
1691#endif
1692#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001693 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001694 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001695 off_t divSize = SHARED_SIZE - 1;
1696
1697 lock.l_type = F_UNLCK;
1698 lock.l_whence = SEEK_SET;
1699 lock.l_start = SHARED_FIRST;
1700 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001701 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001702 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001703 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001704 if( IS_LOCK_ERROR(rc) ){
1705 pFile->lastErrno = tErrno;
1706 }
1707 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001708 }
drh7ed97b92010-01-20 13:07:21 +00001709 lock.l_type = F_RDLCK;
1710 lock.l_whence = SEEK_SET;
1711 lock.l_start = SHARED_FIRST;
1712 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001713 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001714 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001715 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1716 if( IS_LOCK_ERROR(rc) ){
1717 pFile->lastErrno = tErrno;
1718 }
1719 goto end_unlock;
1720 }
1721 lock.l_type = F_UNLCK;
1722 lock.l_whence = SEEK_SET;
1723 lock.l_start = SHARED_FIRST+divSize;
1724 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001725 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001726 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001727 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001728 if( IS_LOCK_ERROR(rc) ){
1729 pFile->lastErrno = tErrno;
1730 }
1731 goto end_unlock;
1732 }
drh30f776f2011-02-25 03:25:07 +00001733 }else
1734#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1735 {
drh7ed97b92010-01-20 13:07:21 +00001736 lock.l_type = F_RDLCK;
1737 lock.l_whence = SEEK_SET;
1738 lock.l_start = SHARED_FIRST;
1739 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001740 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001741 /* In theory, the call to unixFileLock() cannot fail because another
1742 ** process is holding an incompatible lock. If it does, this
1743 ** indicates that the other process is not following the locking
1744 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1745 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1746 ** an assert to fail). */
1747 rc = SQLITE_IOERR_RDLOCK;
1748 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001749 goto end_unlock;
1750 }
drh9c105bb2004-10-02 20:38:28 +00001751 }
1752 }
drhbbd42a62004-05-22 17:41:58 +00001753 lock.l_type = F_UNLCK;
1754 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001755 lock.l_start = PENDING_BYTE;
1756 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001757 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001758 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001759 }else{
danea83bc62011-04-01 11:56:32 +00001760 rc = SQLITE_IOERR_UNLOCK;
1761 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001762 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001763 }
drhbbd42a62004-05-22 17:41:58 +00001764 }
drh308c2a52010-05-14 11:30:18 +00001765 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001766 /* Decrement the shared lock counter. Release the lock using an
1767 ** OS call only when all threads in this same process have released
1768 ** the lock.
1769 */
drh8af6c222010-05-14 12:43:01 +00001770 pInode->nShared--;
1771 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001772 lock.l_type = F_UNLCK;
1773 lock.l_whence = SEEK_SET;
1774 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001775 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001776 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001777 }else{
danea83bc62011-04-01 11:56:32 +00001778 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001779 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001780 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001781 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001782 }
drha6abd042004-06-09 17:37:22 +00001783 }
1784
drhbbd42a62004-05-22 17:41:58 +00001785 /* Decrement the count of locks against this same file. When the
1786 ** count reaches zero, close any other file descriptors whose close
1787 ** was deferred because of outstanding locks.
1788 */
drh8af6c222010-05-14 12:43:01 +00001789 pInode->nLock--;
1790 assert( pInode->nLock>=0 );
1791 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001792 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001793 }
1794 }
drhf2f105d2012-08-20 15:53:54 +00001795
aswift5b1a2562008-08-22 00:22:35 +00001796end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001797 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001798 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001799 return rc;
drhbbd42a62004-05-22 17:41:58 +00001800}
1801
1802/*
drh308c2a52010-05-14 11:30:18 +00001803** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001804** must be either NO_LOCK or SHARED_LOCK.
1805**
1806** If the locking level of the file descriptor is already at or below
1807** the requested locking level, this routine is a no-op.
1808*/
drh308c2a52010-05-14 11:30:18 +00001809static int unixUnlock(sqlite3_file *id, int eFileLock){
dana1afc742013-03-25 13:50:49 +00001810 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
drha7e61d82011-03-12 17:02:57 +00001811 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001812}
1813
danf23da962013-03-23 21:00:41 +00001814static int unixMapfile(unixFile *pFd, i64 nByte);
1815static void unixUnmapfile(unixFile *pFd);
1816
drh7ed97b92010-01-20 13:07:21 +00001817/*
danielk1977e339d652008-06-28 11:23:00 +00001818** This function performs the parts of the "close file" operation
1819** common to all locking schemes. It closes the directory and file
1820** handles, if they are valid, and sets all fields of the unixFile
1821** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001822**
1823** It is *not* necessary to hold the mutex when this routine is called,
1824** even on VxWorks. A mutex will be acquired on VxWorks by the
1825** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001826*/
1827static int closeUnixFile(sqlite3_file *id){
1828 unixFile *pFile = (unixFile*)id;
danf23da962013-03-23 21:00:41 +00001829 unixUnmapfile(pFile);
dan661d71a2011-03-30 19:08:03 +00001830 if( pFile->h>=0 ){
1831 robust_close(pFile, pFile->h, __LINE__);
1832 pFile->h = -1;
1833 }
1834#if OS_VXWORKS
1835 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001836 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001837 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001838 }
1839 vxworksReleaseFileId(pFile->pId);
1840 pFile->pId = 0;
1841 }
1842#endif
1843 OSTRACE(("CLOSE %-3d\n", pFile->h));
1844 OpenCounter(-1);
1845 sqlite3_free(pFile->pUnused);
1846 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001847 return SQLITE_OK;
1848}
1849
1850/*
danielk1977e3026632004-06-22 11:29:02 +00001851** Close a file.
1852*/
danielk197762079062007-08-15 17:08:46 +00001853static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001854 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001855 unixFile *pFile = (unixFile *)id;
1856 unixUnlock(id, NO_LOCK);
1857 unixEnterMutex();
1858
1859 /* unixFile.pInode is always valid here. Otherwise, a different close
1860 ** routine (e.g. nolockClose()) would be called instead.
1861 */
1862 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1863 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1864 /* If there are outstanding locks, do not actually close the file just
1865 ** yet because that would clear those locks. Instead, add the file
1866 ** descriptor to pInode->pUnused list. It will be automatically closed
1867 ** when the last lock is cleared.
1868 */
1869 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001870 }
dan661d71a2011-03-30 19:08:03 +00001871 releaseInodeInfo(pFile);
1872 rc = closeUnixFile(id);
1873 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001874 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001875}
1876
drh734c9862008-11-28 15:37:20 +00001877/************** End of the posix advisory lock implementation *****************
1878******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001879
drh734c9862008-11-28 15:37:20 +00001880/******************************************************************************
1881****************************** No-op Locking **********************************
1882**
1883** Of the various locking implementations available, this is by far the
1884** simplest: locking is ignored. No attempt is made to lock the database
1885** file for reading or writing.
1886**
1887** This locking mode is appropriate for use on read-only databases
1888** (ex: databases that are burned into CD-ROM, for example.) It can
1889** also be used if the application employs some external mechanism to
1890** prevent simultaneous access of the same database by two or more
1891** database connections. But there is a serious risk of database
1892** corruption if this locking mode is used in situations where multiple
1893** database connections are accessing the same database file at the same
1894** time and one or more of those connections are writing.
1895*/
drhbfe66312006-10-03 17:40:40 +00001896
drh734c9862008-11-28 15:37:20 +00001897static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1898 UNUSED_PARAMETER(NotUsed);
1899 *pResOut = 0;
1900 return SQLITE_OK;
1901}
drh734c9862008-11-28 15:37:20 +00001902static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1903 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1904 return SQLITE_OK;
1905}
drh734c9862008-11-28 15:37:20 +00001906static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1907 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1908 return SQLITE_OK;
1909}
1910
1911/*
drh9b35ea62008-11-29 02:20:26 +00001912** Close the file.
drh734c9862008-11-28 15:37:20 +00001913*/
1914static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001915 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001916}
1917
1918/******************* End of the no-op lock implementation *********************
1919******************************************************************************/
1920
1921/******************************************************************************
1922************************* Begin dot-file Locking ******************************
1923**
drh0c2694b2009-09-03 16:23:44 +00001924** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001925** files (really a directory) to control access to the database. This works
1926** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001927**
1928** (1) There is zero concurrency. A single reader blocks all other
1929** connections from reading or writing the database.
1930**
1931** (2) An application crash or power loss can leave stale lock files
1932** sitting around that need to be cleared manually.
1933**
1934** Nevertheless, a dotlock is an appropriate locking mode for use if no
1935** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001936**
drh9ef6bc42011-11-04 02:24:02 +00001937** Dotfile locking works by creating a subdirectory in the same directory as
1938** the database and with the same name but with a ".lock" extension added.
1939** The existance of a lock directory implies an EXCLUSIVE lock. All other
1940** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001941*/
1942
1943/*
1944** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001945** lock directory.
drh734c9862008-11-28 15:37:20 +00001946*/
1947#define DOTLOCK_SUFFIX ".lock"
1948
drh7708e972008-11-29 00:56:52 +00001949/*
1950** This routine checks if there is a RESERVED lock held on the specified
1951** file by this or any other process. If such a lock is held, set *pResOut
1952** to a non-zero value otherwise *pResOut is set to zero. The return value
1953** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1954**
1955** In dotfile locking, either a lock exists or it does not. So in this
1956** variation of CheckReservedLock(), *pResOut is set to true if any lock
1957** is held on the file and false if the file is unlocked.
1958*/
drh734c9862008-11-28 15:37:20 +00001959static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1960 int rc = SQLITE_OK;
1961 int reserved = 0;
1962 unixFile *pFile = (unixFile*)id;
1963
1964 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1965
1966 assert( pFile );
1967
1968 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001969 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001970 /* Either this connection or some other connection in the same process
1971 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001972 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001973 }else{
1974 /* The lock is held if and only if the lockfile exists */
1975 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001976 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001977 }
drh308c2a52010-05-14 11:30:18 +00001978 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001979 *pResOut = reserved;
1980 return rc;
1981}
1982
drh7708e972008-11-29 00:56:52 +00001983/*
drh308c2a52010-05-14 11:30:18 +00001984** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001985** of the following:
1986**
1987** (1) SHARED_LOCK
1988** (2) RESERVED_LOCK
1989** (3) PENDING_LOCK
1990** (4) EXCLUSIVE_LOCK
1991**
1992** Sometimes when requesting one lock state, additional lock states
1993** are inserted in between. The locking might fail on one of the later
1994** transitions leaving the lock state different from what it started but
1995** still short of its goal. The following chart shows the allowed
1996** transitions and the inserted intermediate states:
1997**
1998** UNLOCKED -> SHARED
1999** SHARED -> RESERVED
2000** SHARED -> (PENDING) -> EXCLUSIVE
2001** RESERVED -> (PENDING) -> EXCLUSIVE
2002** PENDING -> EXCLUSIVE
2003**
2004** This routine will only increase a lock. Use the sqlite3OsUnlock()
2005** routine to lower a locking level.
2006**
2007** With dotfile locking, we really only support state (4): EXCLUSIVE.
2008** But we track the other locking levels internally.
2009*/
drh308c2a52010-05-14 11:30:18 +00002010static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002011 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002012 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002013 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002014
drh7708e972008-11-29 00:56:52 +00002015
2016 /* If we have any lock, then the lock file already exists. All we have
2017 ** to do is adjust our internal record of the lock level.
2018 */
drh308c2a52010-05-14 11:30:18 +00002019 if( pFile->eFileLock > NO_LOCK ){
2020 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002021 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002022#ifdef HAVE_UTIME
2023 utime(zLockFile, NULL);
2024#else
drh734c9862008-11-28 15:37:20 +00002025 utimes(zLockFile, NULL);
2026#endif
drh7708e972008-11-29 00:56:52 +00002027 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002028 }
2029
2030 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002031 rc = osMkdir(zLockFile, 0777);
2032 if( rc<0 ){
2033 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002034 int tErrno = errno;
2035 if( EEXIST == tErrno ){
2036 rc = SQLITE_BUSY;
2037 } else {
2038 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2039 if( IS_LOCK_ERROR(rc) ){
2040 pFile->lastErrno = tErrno;
2041 }
2042 }
drh7708e972008-11-29 00:56:52 +00002043 return rc;
drh734c9862008-11-28 15:37:20 +00002044 }
drh734c9862008-11-28 15:37:20 +00002045
2046 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002047 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002048 return rc;
2049}
2050
drh7708e972008-11-29 00:56:52 +00002051/*
drh308c2a52010-05-14 11:30:18 +00002052** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002053** must be either NO_LOCK or SHARED_LOCK.
2054**
2055** If the locking level of the file descriptor is already at or below
2056** the requested locking level, this routine is a no-op.
2057**
2058** When the locking level reaches NO_LOCK, delete the lock file.
2059*/
drh308c2a52010-05-14 11:30:18 +00002060static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002061 unixFile *pFile = (unixFile*)id;
2062 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002063 int rc;
drh734c9862008-11-28 15:37:20 +00002064
2065 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002066 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002067 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002068 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002069
2070 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002071 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002072 return SQLITE_OK;
2073 }
drh7708e972008-11-29 00:56:52 +00002074
2075 /* To downgrade to shared, simply update our internal notion of the
2076 ** lock state. No need to mess with the file on disk.
2077 */
drh308c2a52010-05-14 11:30:18 +00002078 if( eFileLock==SHARED_LOCK ){
2079 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002080 return SQLITE_OK;
2081 }
2082
drh7708e972008-11-29 00:56:52 +00002083 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002084 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002085 rc = osRmdir(zLockFile);
2086 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2087 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002088 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002089 rc = 0;
drh734c9862008-11-28 15:37:20 +00002090 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002091 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002092 }
2093 if( IS_LOCK_ERROR(rc) ){
2094 pFile->lastErrno = tErrno;
2095 }
2096 return rc;
2097 }
drh308c2a52010-05-14 11:30:18 +00002098 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002099 return SQLITE_OK;
2100}
2101
2102/*
drh9b35ea62008-11-29 02:20:26 +00002103** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002104*/
2105static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002106 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002107 if( id ){
2108 unixFile *pFile = (unixFile*)id;
2109 dotlockUnlock(id, NO_LOCK);
2110 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002111 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002112 }
drh734c9862008-11-28 15:37:20 +00002113 return rc;
2114}
2115/****************** End of the dot-file lock implementation *******************
2116******************************************************************************/
2117
2118/******************************************************************************
2119************************** Begin flock Locking ********************************
2120**
2121** Use the flock() system call to do file locking.
2122**
drh6b9d6dd2008-12-03 19:34:47 +00002123** flock() locking is like dot-file locking in that the various
2124** fine-grain locking levels supported by SQLite are collapsed into
2125** a single exclusive lock. In other words, SHARED, RESERVED, and
2126** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2127** still works when you do this, but concurrency is reduced since
2128** only a single process can be reading the database at a time.
2129**
drh734c9862008-11-28 15:37:20 +00002130** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2131** compiling for VXWORKS.
2132*/
2133#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002134
drh6b9d6dd2008-12-03 19:34:47 +00002135/*
drhff812312011-02-23 13:33:46 +00002136** Retry flock() calls that fail with EINTR
2137*/
2138#ifdef EINTR
2139static int robust_flock(int fd, int op){
2140 int rc;
2141 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2142 return rc;
2143}
2144#else
drh5c819272011-02-23 14:00:12 +00002145# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002146#endif
2147
2148
2149/*
drh6b9d6dd2008-12-03 19:34:47 +00002150** This routine checks if there is a RESERVED lock held on the specified
2151** file by this or any other process. If such a lock is held, set *pResOut
2152** to a non-zero value otherwise *pResOut is set to zero. The return value
2153** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2154*/
drh734c9862008-11-28 15:37:20 +00002155static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2156 int rc = SQLITE_OK;
2157 int reserved = 0;
2158 unixFile *pFile = (unixFile*)id;
2159
2160 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2161
2162 assert( pFile );
2163
2164 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002165 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002166 reserved = 1;
2167 }
2168
2169 /* Otherwise see if some other process holds it. */
2170 if( !reserved ){
2171 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002172 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002173 if( !lrc ){
2174 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002175 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002176 if ( lrc ) {
2177 int tErrno = errno;
2178 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002179 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002180 if( IS_LOCK_ERROR(lrc) ){
2181 pFile->lastErrno = tErrno;
2182 rc = lrc;
2183 }
2184 }
2185 } else {
2186 int tErrno = errno;
2187 reserved = 1;
2188 /* someone else might have it reserved */
2189 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2190 if( IS_LOCK_ERROR(lrc) ){
2191 pFile->lastErrno = tErrno;
2192 rc = lrc;
2193 }
2194 }
2195 }
drh308c2a52010-05-14 11:30:18 +00002196 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002197
2198#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2199 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2200 rc = SQLITE_OK;
2201 reserved=1;
2202 }
2203#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2204 *pResOut = reserved;
2205 return rc;
2206}
2207
drh6b9d6dd2008-12-03 19:34:47 +00002208/*
drh308c2a52010-05-14 11:30:18 +00002209** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002210** of the following:
2211**
2212** (1) SHARED_LOCK
2213** (2) RESERVED_LOCK
2214** (3) PENDING_LOCK
2215** (4) EXCLUSIVE_LOCK
2216**
2217** Sometimes when requesting one lock state, additional lock states
2218** are inserted in between. The locking might fail on one of the later
2219** transitions leaving the lock state different from what it started but
2220** still short of its goal. The following chart shows the allowed
2221** transitions and the inserted intermediate states:
2222**
2223** UNLOCKED -> SHARED
2224** SHARED -> RESERVED
2225** SHARED -> (PENDING) -> EXCLUSIVE
2226** RESERVED -> (PENDING) -> EXCLUSIVE
2227** PENDING -> EXCLUSIVE
2228**
2229** flock() only really support EXCLUSIVE locks. We track intermediate
2230** lock states in the sqlite3_file structure, but all locks SHARED or
2231** above are really EXCLUSIVE locks and exclude all other processes from
2232** access the file.
2233**
2234** This routine will only increase a lock. Use the sqlite3OsUnlock()
2235** routine to lower a locking level.
2236*/
drh308c2a52010-05-14 11:30:18 +00002237static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002238 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002239 unixFile *pFile = (unixFile*)id;
2240
2241 assert( pFile );
2242
2243 /* if we already have a lock, it is exclusive.
2244 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002245 if (pFile->eFileLock > NO_LOCK) {
2246 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002247 return SQLITE_OK;
2248 }
2249
2250 /* grab an exclusive lock */
2251
drhff812312011-02-23 13:33:46 +00002252 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002253 int tErrno = errno;
2254 /* didn't get, must be busy */
2255 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2256 if( IS_LOCK_ERROR(rc) ){
2257 pFile->lastErrno = tErrno;
2258 }
2259 } else {
2260 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002261 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002262 }
drh308c2a52010-05-14 11:30:18 +00002263 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2264 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002265#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2266 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2267 rc = SQLITE_BUSY;
2268 }
2269#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2270 return rc;
2271}
2272
drh6b9d6dd2008-12-03 19:34:47 +00002273
2274/*
drh308c2a52010-05-14 11:30:18 +00002275** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002276** must be either NO_LOCK or SHARED_LOCK.
2277**
2278** If the locking level of the file descriptor is already at or below
2279** the requested locking level, this routine is a no-op.
2280*/
drh308c2a52010-05-14 11:30:18 +00002281static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002282 unixFile *pFile = (unixFile*)id;
2283
2284 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002285 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2286 pFile->eFileLock, getpid()));
2287 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002288
2289 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002290 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002291 return SQLITE_OK;
2292 }
2293
2294 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002295 if (eFileLock==SHARED_LOCK) {
2296 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002297 return SQLITE_OK;
2298 }
2299
2300 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002301 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002302#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002303 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002304#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002305 return SQLITE_IOERR_UNLOCK;
2306 }else{
drh308c2a52010-05-14 11:30:18 +00002307 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002308 return SQLITE_OK;
2309 }
2310}
2311
2312/*
2313** Close a file.
2314*/
2315static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002316 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002317 if( id ){
2318 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002319 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002320 }
drh5a05be12012-10-09 18:51:44 +00002321 return rc;
drh734c9862008-11-28 15:37:20 +00002322}
2323
2324#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2325
2326/******************* End of the flock lock implementation *********************
2327******************************************************************************/
2328
2329/******************************************************************************
2330************************ Begin Named Semaphore Locking ************************
2331**
2332** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002333**
2334** Semaphore locking is like dot-lock and flock in that it really only
2335** supports EXCLUSIVE locking. Only a single process can read or write
2336** the database file at a time. This reduces potential concurrency, but
2337** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002338*/
2339#if OS_VXWORKS
2340
drh6b9d6dd2008-12-03 19:34:47 +00002341/*
2342** This routine checks if there is a RESERVED lock held on the specified
2343** file by this or any other process. If such a lock is held, set *pResOut
2344** to a non-zero value otherwise *pResOut is set to zero. The return value
2345** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2346*/
drh734c9862008-11-28 15:37:20 +00002347static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2348 int rc = SQLITE_OK;
2349 int reserved = 0;
2350 unixFile *pFile = (unixFile*)id;
2351
2352 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2353
2354 assert( pFile );
2355
2356 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002357 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002358 reserved = 1;
2359 }
2360
2361 /* Otherwise see if some other process holds it. */
2362 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002363 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002364 struct stat statBuf;
2365
2366 if( sem_trywait(pSem)==-1 ){
2367 int tErrno = errno;
2368 if( EAGAIN != tErrno ){
2369 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2370 pFile->lastErrno = tErrno;
2371 } else {
2372 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002373 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002374 }
2375 }else{
2376 /* we could have it if we want it */
2377 sem_post(pSem);
2378 }
2379 }
drh308c2a52010-05-14 11:30:18 +00002380 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002381
2382 *pResOut = reserved;
2383 return rc;
2384}
2385
drh6b9d6dd2008-12-03 19:34:47 +00002386/*
drh308c2a52010-05-14 11:30:18 +00002387** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002388** of the following:
2389**
2390** (1) SHARED_LOCK
2391** (2) RESERVED_LOCK
2392** (3) PENDING_LOCK
2393** (4) EXCLUSIVE_LOCK
2394**
2395** Sometimes when requesting one lock state, additional lock states
2396** are inserted in between. The locking might fail on one of the later
2397** transitions leaving the lock state different from what it started but
2398** still short of its goal. The following chart shows the allowed
2399** transitions and the inserted intermediate states:
2400**
2401** UNLOCKED -> SHARED
2402** SHARED -> RESERVED
2403** SHARED -> (PENDING) -> EXCLUSIVE
2404** RESERVED -> (PENDING) -> EXCLUSIVE
2405** PENDING -> EXCLUSIVE
2406**
2407** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2408** lock states in the sqlite3_file structure, but all locks SHARED or
2409** above are really EXCLUSIVE locks and exclude all other processes from
2410** access the file.
2411**
2412** This routine will only increase a lock. Use the sqlite3OsUnlock()
2413** routine to lower a locking level.
2414*/
drh308c2a52010-05-14 11:30:18 +00002415static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002416 unixFile *pFile = (unixFile*)id;
2417 int fd;
drh8af6c222010-05-14 12:43:01 +00002418 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002419 int rc = SQLITE_OK;
2420
2421 /* if we already have a lock, it is exclusive.
2422 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002423 if (pFile->eFileLock > NO_LOCK) {
2424 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002425 rc = SQLITE_OK;
2426 goto sem_end_lock;
2427 }
2428
2429 /* lock semaphore now but bail out when already locked. */
2430 if( sem_trywait(pSem)==-1 ){
2431 rc = SQLITE_BUSY;
2432 goto sem_end_lock;
2433 }
2434
2435 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002436 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002437
2438 sem_end_lock:
2439 return rc;
2440}
2441
drh6b9d6dd2008-12-03 19:34:47 +00002442/*
drh308c2a52010-05-14 11:30:18 +00002443** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002444** must be either NO_LOCK or SHARED_LOCK.
2445**
2446** If the locking level of the file descriptor is already at or below
2447** the requested locking level, this routine is a no-op.
2448*/
drh308c2a52010-05-14 11:30:18 +00002449static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002450 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002451 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002452
2453 assert( pFile );
2454 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002455 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002456 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002457 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002458
2459 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002460 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002461 return SQLITE_OK;
2462 }
2463
2464 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002465 if (eFileLock==SHARED_LOCK) {
2466 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002467 return SQLITE_OK;
2468 }
2469
2470 /* no, really unlock. */
2471 if ( sem_post(pSem)==-1 ) {
2472 int rc, tErrno = errno;
2473 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2474 if( IS_LOCK_ERROR(rc) ){
2475 pFile->lastErrno = tErrno;
2476 }
2477 return rc;
2478 }
drh308c2a52010-05-14 11:30:18 +00002479 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002480 return SQLITE_OK;
2481}
2482
2483/*
2484 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002485 */
drh734c9862008-11-28 15:37:20 +00002486static int semClose(sqlite3_file *id) {
2487 if( id ){
2488 unixFile *pFile = (unixFile*)id;
2489 semUnlock(id, NO_LOCK);
2490 assert( pFile );
2491 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002492 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002493 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002494 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002495 }
2496 return SQLITE_OK;
2497}
2498
2499#endif /* OS_VXWORKS */
2500/*
2501** Named semaphore locking is only available on VxWorks.
2502**
2503*************** End of the named semaphore lock implementation ****************
2504******************************************************************************/
2505
2506
2507/******************************************************************************
2508*************************** Begin AFP Locking *********************************
2509**
2510** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2511** on Apple Macintosh computers - both OS9 and OSX.
2512**
2513** Third-party implementations of AFP are available. But this code here
2514** only works on OSX.
2515*/
2516
drhd2cb50b2009-01-09 21:41:17 +00002517#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002518/*
2519** The afpLockingContext structure contains all afp lock specific state
2520*/
drhbfe66312006-10-03 17:40:40 +00002521typedef struct afpLockingContext afpLockingContext;
2522struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002523 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002524 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002525};
2526
2527struct ByteRangeLockPB2
2528{
2529 unsigned long long offset; /* offset to first byte to lock */
2530 unsigned long long length; /* nbr of bytes to lock */
2531 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2532 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2533 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2534 int fd; /* file desc to assoc this lock with */
2535};
2536
drhfd131da2007-08-07 17:13:03 +00002537#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002538
drh6b9d6dd2008-12-03 19:34:47 +00002539/*
2540** This is a utility for setting or clearing a bit-range lock on an
2541** AFP filesystem.
2542**
2543** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2544*/
2545static int afpSetLock(
2546 const char *path, /* Name of the file to be locked or unlocked */
2547 unixFile *pFile, /* Open file descriptor on path */
2548 unsigned long long offset, /* First byte to be locked */
2549 unsigned long long length, /* Number of bytes to lock */
2550 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002551){
drh6b9d6dd2008-12-03 19:34:47 +00002552 struct ByteRangeLockPB2 pb;
2553 int err;
drhbfe66312006-10-03 17:40:40 +00002554
2555 pb.unLockFlag = setLockFlag ? 0 : 1;
2556 pb.startEndFlag = 0;
2557 pb.offset = offset;
2558 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002559 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002560
drh308c2a52010-05-14 11:30:18 +00002561 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002562 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002563 offset, length));
drhbfe66312006-10-03 17:40:40 +00002564 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2565 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002566 int rc;
2567 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002568 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2569 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002570#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2571 rc = SQLITE_BUSY;
2572#else
drh734c9862008-11-28 15:37:20 +00002573 rc = sqliteErrorFromPosixError(tErrno,
2574 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002575#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002576 if( IS_LOCK_ERROR(rc) ){
2577 pFile->lastErrno = tErrno;
2578 }
2579 return rc;
drhbfe66312006-10-03 17:40:40 +00002580 } else {
aswift5b1a2562008-08-22 00:22:35 +00002581 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002582 }
2583}
2584
drh6b9d6dd2008-12-03 19:34:47 +00002585/*
2586** This routine checks if there is a RESERVED lock held on the specified
2587** file by this or any other process. If such a lock is held, set *pResOut
2588** to a non-zero value otherwise *pResOut is set to zero. The return value
2589** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2590*/
danielk1977e339d652008-06-28 11:23:00 +00002591static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002592 int rc = SQLITE_OK;
2593 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002594 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002595 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002596
aswift5b1a2562008-08-22 00:22:35 +00002597 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2598
2599 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002600 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002601 if( context->reserved ){
2602 *pResOut = 1;
2603 return SQLITE_OK;
2604 }
drh8af6c222010-05-14 12:43:01 +00002605 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002606
2607 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002608 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002609 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002610 }
2611
2612 /* Otherwise see if some other process holds it.
2613 */
aswift5b1a2562008-08-22 00:22:35 +00002614 if( !reserved ){
2615 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002616 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002617 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002618 /* if we succeeded in taking the reserved lock, unlock it to restore
2619 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002620 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002621 } else {
2622 /* if we failed to get the lock then someone else must have it */
2623 reserved = 1;
2624 }
2625 if( IS_LOCK_ERROR(lrc) ){
2626 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002627 }
2628 }
drhbfe66312006-10-03 17:40:40 +00002629
drh7ed97b92010-01-20 13:07:21 +00002630 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002631 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002632
2633 *pResOut = reserved;
2634 return rc;
drhbfe66312006-10-03 17:40:40 +00002635}
2636
drh6b9d6dd2008-12-03 19:34:47 +00002637/*
drh308c2a52010-05-14 11:30:18 +00002638** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002639** of the following:
2640**
2641** (1) SHARED_LOCK
2642** (2) RESERVED_LOCK
2643** (3) PENDING_LOCK
2644** (4) EXCLUSIVE_LOCK
2645**
2646** Sometimes when requesting one lock state, additional lock states
2647** are inserted in between. The locking might fail on one of the later
2648** transitions leaving the lock state different from what it started but
2649** still short of its goal. The following chart shows the allowed
2650** transitions and the inserted intermediate states:
2651**
2652** UNLOCKED -> SHARED
2653** SHARED -> RESERVED
2654** SHARED -> (PENDING) -> EXCLUSIVE
2655** RESERVED -> (PENDING) -> EXCLUSIVE
2656** PENDING -> EXCLUSIVE
2657**
2658** This routine will only increase a lock. Use the sqlite3OsUnlock()
2659** routine to lower a locking level.
2660*/
drh308c2a52010-05-14 11:30:18 +00002661static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002662 int rc = SQLITE_OK;
2663 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002664 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002665 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002666
2667 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002668 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2669 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002670 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002671
drhbfe66312006-10-03 17:40:40 +00002672 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002673 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002674 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002675 */
drh308c2a52010-05-14 11:30:18 +00002676 if( pFile->eFileLock>=eFileLock ){
2677 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2678 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002679 return SQLITE_OK;
2680 }
2681
2682 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002683 ** (1) We never move from unlocked to anything higher than shared lock.
2684 ** (2) SQLite never explicitly requests a pendig lock.
2685 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002686 */
drh308c2a52010-05-14 11:30:18 +00002687 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2688 assert( eFileLock!=PENDING_LOCK );
2689 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002690
drh8af6c222010-05-14 12:43:01 +00002691 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002692 */
drh6c7d5c52008-11-21 20:32:33 +00002693 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002694 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002695
2696 /* If some thread using this PID has a lock via a different unixFile*
2697 ** handle that precludes the requested lock, return BUSY.
2698 */
drh8af6c222010-05-14 12:43:01 +00002699 if( (pFile->eFileLock!=pInode->eFileLock &&
2700 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002701 ){
2702 rc = SQLITE_BUSY;
2703 goto afp_end_lock;
2704 }
2705
2706 /* If a SHARED lock is requested, and some thread using this PID already
2707 ** has a SHARED or RESERVED lock, then increment reference counts and
2708 ** return SQLITE_OK.
2709 */
drh308c2a52010-05-14 11:30:18 +00002710 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002711 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002712 assert( eFileLock==SHARED_LOCK );
2713 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002714 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002715 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002716 pInode->nShared++;
2717 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002718 goto afp_end_lock;
2719 }
drhbfe66312006-10-03 17:40:40 +00002720
2721 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002722 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2723 ** be released.
2724 */
drh308c2a52010-05-14 11:30:18 +00002725 if( eFileLock==SHARED_LOCK
2726 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002727 ){
2728 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002729 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002730 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002731 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002732 goto afp_end_lock;
2733 }
2734 }
2735
2736 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002737 ** operating system calls for the specified lock.
2738 */
drh308c2a52010-05-14 11:30:18 +00002739 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002740 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002741 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002742
drh8af6c222010-05-14 12:43:01 +00002743 assert( pInode->nShared==0 );
2744 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002745
2746 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002747 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002748 /* note that the quality of the randomness doesn't matter that much */
2749 lk = random();
drh8af6c222010-05-14 12:43:01 +00002750 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002751 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002752 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002753 if( IS_LOCK_ERROR(lrc1) ){
2754 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002755 }
aswift5b1a2562008-08-22 00:22:35 +00002756 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002757 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002758
aswift5b1a2562008-08-22 00:22:35 +00002759 if( IS_LOCK_ERROR(lrc1) ) {
2760 pFile->lastErrno = lrc1Errno;
2761 rc = lrc1;
2762 goto afp_end_lock;
2763 } else if( IS_LOCK_ERROR(lrc2) ){
2764 rc = lrc2;
2765 goto afp_end_lock;
2766 } else if( lrc1 != SQLITE_OK ) {
2767 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002768 } else {
drh308c2a52010-05-14 11:30:18 +00002769 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002770 pInode->nLock++;
2771 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002772 }
drh8af6c222010-05-14 12:43:01 +00002773 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002774 /* We are trying for an exclusive lock but another thread in this
2775 ** same process is still holding a shared lock. */
2776 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002777 }else{
2778 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2779 ** assumed that there is a SHARED or greater lock on the file
2780 ** already.
2781 */
2782 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002783 assert( 0!=pFile->eFileLock );
2784 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002785 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002786 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002787 if( !failed ){
2788 context->reserved = 1;
2789 }
drhbfe66312006-10-03 17:40:40 +00002790 }
drh308c2a52010-05-14 11:30:18 +00002791 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002792 /* Acquire an EXCLUSIVE lock */
2793
2794 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002795 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002796 */
drh6b9d6dd2008-12-03 19:34:47 +00002797 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002798 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002799 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002800 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002801 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002802 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002803 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002804 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002805 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2806 ** a critical I/O error
2807 */
2808 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2809 SQLITE_IOERR_LOCK;
2810 goto afp_end_lock;
2811 }
2812 }else{
aswift5b1a2562008-08-22 00:22:35 +00002813 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002814 }
2815 }
aswift5b1a2562008-08-22 00:22:35 +00002816 if( failed ){
2817 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002818 }
2819 }
2820
2821 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002822 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002823 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002824 }else if( eFileLock==EXCLUSIVE_LOCK ){
2825 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002826 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002827 }
2828
2829afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002830 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002831 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2832 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002833 return rc;
2834}
2835
2836/*
drh308c2a52010-05-14 11:30:18 +00002837** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002838** must be either NO_LOCK or SHARED_LOCK.
2839**
2840** If the locking level of the file descriptor is already at or below
2841** the requested locking level, this routine is a no-op.
2842*/
drh308c2a52010-05-14 11:30:18 +00002843static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002844 int rc = SQLITE_OK;
2845 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002846 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002847 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2848 int skipShared = 0;
2849#ifdef SQLITE_TEST
2850 int h = pFile->h;
2851#endif
drhbfe66312006-10-03 17:40:40 +00002852
2853 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002854 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002855 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002856 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002857
drh308c2a52010-05-14 11:30:18 +00002858 assert( eFileLock<=SHARED_LOCK );
2859 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002860 return SQLITE_OK;
2861 }
drh6c7d5c52008-11-21 20:32:33 +00002862 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002863 pInode = pFile->pInode;
2864 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002865 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002866 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002867 SimulateIOErrorBenign(1);
2868 SimulateIOError( h=(-1) )
2869 SimulateIOErrorBenign(0);
2870
drhd3d8c042012-05-29 17:02:40 +00002871#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002872 /* When reducing a lock such that other processes can start
2873 ** reading the database file again, make sure that the
2874 ** transaction counter was updated if any part of the database
2875 ** file changed. If the transaction counter is not updated,
2876 ** other connections to the same file might not realize that
2877 ** the file has changed and hence might not know to flush their
2878 ** cache. The use of a stale cache can lead to database corruption.
2879 */
2880 assert( pFile->inNormalWrite==0
2881 || pFile->dbUpdate==0
2882 || pFile->transCntrChng==1 );
2883 pFile->inNormalWrite = 0;
2884#endif
aswiftaebf4132008-11-21 00:10:35 +00002885
drh308c2a52010-05-14 11:30:18 +00002886 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002887 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002888 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002889 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002890 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002891 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2892 } else {
2893 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002894 }
2895 }
drh308c2a52010-05-14 11:30:18 +00002896 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002897 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002898 }
drh308c2a52010-05-14 11:30:18 +00002899 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002900 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2901 if( !rc ){
2902 context->reserved = 0;
2903 }
aswiftaebf4132008-11-21 00:10:35 +00002904 }
drh8af6c222010-05-14 12:43:01 +00002905 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2906 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002907 }
aswiftaebf4132008-11-21 00:10:35 +00002908 }
drh308c2a52010-05-14 11:30:18 +00002909 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002910
drh7ed97b92010-01-20 13:07:21 +00002911 /* Decrement the shared lock counter. Release the lock using an
2912 ** OS call only when all threads in this same process have released
2913 ** the lock.
2914 */
drh8af6c222010-05-14 12:43:01 +00002915 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2916 pInode->nShared--;
2917 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002918 SimulateIOErrorBenign(1);
2919 SimulateIOError( h=(-1) )
2920 SimulateIOErrorBenign(0);
2921 if( !skipShared ){
2922 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2923 }
2924 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002925 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002926 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002927 }
2928 }
2929 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002930 pInode->nLock--;
2931 assert( pInode->nLock>=0 );
2932 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002933 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002934 }
2935 }
drhbfe66312006-10-03 17:40:40 +00002936 }
drh7ed97b92010-01-20 13:07:21 +00002937
drh6c7d5c52008-11-21 20:32:33 +00002938 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002939 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002940 return rc;
2941}
2942
2943/*
drh339eb0b2008-03-07 15:34:11 +00002944** Close a file & cleanup AFP specific locking context
2945*/
danielk1977e339d652008-06-28 11:23:00 +00002946static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002947 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002948 if( id ){
2949 unixFile *pFile = (unixFile*)id;
2950 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002951 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002952 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002953 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002954 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002955 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002956 ** the last lock is cleared.
2957 */
dan08da86a2009-08-21 17:18:03 +00002958 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002959 }
danb0ac3e32010-06-16 10:55:42 +00002960 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002961 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002962 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002963 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002964 }
drh7ed97b92010-01-20 13:07:21 +00002965 return rc;
drhbfe66312006-10-03 17:40:40 +00002966}
2967
drhd2cb50b2009-01-09 21:41:17 +00002968#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002969/*
2970** The code above is the AFP lock implementation. The code is specific
2971** to MacOSX and does not work on other unix platforms. No alternative
2972** is available. If you don't compile for a mac, then the "unix-afp"
2973** VFS is not available.
2974**
2975********************* End of the AFP lock implementation **********************
2976******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002977
drh7ed97b92010-01-20 13:07:21 +00002978/******************************************************************************
2979*************************** Begin NFS Locking ********************************/
2980
2981#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2982/*
drh308c2a52010-05-14 11:30:18 +00002983 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002984 ** must be either NO_LOCK or SHARED_LOCK.
2985 **
2986 ** If the locking level of the file descriptor is already at or below
2987 ** the requested locking level, this routine is a no-op.
2988 */
drh308c2a52010-05-14 11:30:18 +00002989static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002990 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002991}
2992
2993#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2994/*
2995** The code above is the NFS lock implementation. The code is specific
2996** to MacOSX and does not work on other unix platforms. No alternative
2997** is available.
2998**
2999********************* End of the NFS lock implementation **********************
3000******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003001
3002/******************************************************************************
3003**************** Non-locking sqlite3_file methods *****************************
3004**
3005** The next division contains implementations for all methods of the
3006** sqlite3_file object other than the locking methods. The locking
3007** methods were defined in divisions above (one locking method per
3008** division). Those methods that are common to all locking modes
3009** are gather together into this division.
3010*/
drhbfe66312006-10-03 17:40:40 +00003011
3012/*
drh734c9862008-11-28 15:37:20 +00003013** Seek to the offset passed as the second argument, then read cnt
3014** bytes into pBuf. Return the number of bytes actually read.
3015**
3016** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3017** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3018** one system to another. Since SQLite does not define USE_PREAD
3019** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3020** See tickets #2741 and #2681.
3021**
3022** To avoid stomping the errno value on a failed read the lastErrno value
3023** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003024*/
drh734c9862008-11-28 15:37:20 +00003025static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3026 int got;
drh58024642011-11-07 18:16:00 +00003027 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003028#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003029 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003030#endif
drh734c9862008-11-28 15:37:20 +00003031 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003032 assert( cnt==(cnt&0x1ffff) );
3033 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003034 do{
drh734c9862008-11-28 15:37:20 +00003035#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003036 got = osPread(id->h, pBuf, cnt, offset);
3037 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003038#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003039 got = osPread64(id->h, pBuf, cnt, offset);
3040 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003041#else
drh58024642011-11-07 18:16:00 +00003042 newOffset = lseek(id->h, offset, SEEK_SET);
3043 SimulateIOError( newOffset-- );
3044 if( newOffset!=offset ){
3045 if( newOffset == -1 ){
3046 ((unixFile*)id)->lastErrno = errno;
3047 }else{
drhf2f105d2012-08-20 15:53:54 +00003048 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003049 }
3050 return -1;
drh734c9862008-11-28 15:37:20 +00003051 }
drh58024642011-11-07 18:16:00 +00003052 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003053#endif
drh58024642011-11-07 18:16:00 +00003054 if( got==cnt ) break;
3055 if( got<0 ){
3056 if( errno==EINTR ){ got = 1; continue; }
3057 prior = 0;
3058 ((unixFile*)id)->lastErrno = errno;
3059 break;
3060 }else if( got>0 ){
3061 cnt -= got;
3062 offset += got;
3063 prior += got;
3064 pBuf = (void*)(got + (char*)pBuf);
3065 }
3066 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003067 TIMER_END;
drh58024642011-11-07 18:16:00 +00003068 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3069 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3070 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003071}
3072
3073/*
drh734c9862008-11-28 15:37:20 +00003074** Read data from a file into a buffer. Return SQLITE_OK if all
3075** bytes were read successfully and SQLITE_IOERR if anything goes
3076** wrong.
drh339eb0b2008-03-07 15:34:11 +00003077*/
drh734c9862008-11-28 15:37:20 +00003078static int unixRead(
3079 sqlite3_file *id,
3080 void *pBuf,
3081 int amt,
3082 sqlite3_int64 offset
3083){
dan08da86a2009-08-21 17:18:03 +00003084 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003085 int got;
3086 assert( id );
drh08c6d442009-02-09 17:34:07 +00003087
dan08da86a2009-08-21 17:18:03 +00003088 /* If this is a database file (not a journal, master-journal or temp
3089 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003090#if 0
dane946c392009-08-22 11:39:46 +00003091 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003092 || offset>=PENDING_BYTE+512
3093 || offset+amt<=PENDING_BYTE
3094 );
dan7c246102010-04-12 19:00:29 +00003095#endif
drh08c6d442009-02-09 17:34:07 +00003096
danf23da962013-03-23 21:00:41 +00003097 /* Deal with as much of this write request as possible by transfering
3098 ** data to the memory mapping using memcpy(). */
3099 if( offset<pFile->mmapSize ){
3100 if( offset+amt <= pFile->mmapSize ){
3101 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3102 return SQLITE_OK;
3103 }else{
3104 int nCopy = pFile->mmapSize - offset;
3105 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3106 pBuf = &((u8 *)pBuf)[nCopy];
3107 amt -= nCopy;
3108 offset += nCopy;
3109 }
3110 }
3111
dan08da86a2009-08-21 17:18:03 +00003112 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003113 if( got==amt ){
3114 return SQLITE_OK;
3115 }else if( got<0 ){
3116 /* lastErrno set by seekAndRead */
3117 return SQLITE_IOERR_READ;
3118 }else{
dan08da86a2009-08-21 17:18:03 +00003119 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003120 /* Unread parts of the buffer must be zero-filled */
3121 memset(&((char*)pBuf)[got], 0, amt-got);
3122 return SQLITE_IOERR_SHORT_READ;
3123 }
3124}
3125
3126/*
3127** Seek to the offset in id->offset then read cnt bytes into pBuf.
3128** Return the number of bytes actually read. Update the offset.
3129**
3130** To avoid stomping the errno value on a failed write the lastErrno value
3131** is set before returning.
3132*/
3133static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3134 int got;
drh7ed97b92010-01-20 13:07:21 +00003135#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003136 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003137#endif
drhc1fd2cf2012-10-01 12:16:26 +00003138 assert( cnt==(cnt&0x1ffff) );
3139 cnt &= 0x1ffff;
drh734c9862008-11-28 15:37:20 +00003140 TIMER_START;
3141#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003142 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003143#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003144 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003145#else
drhbd1e50c2011-08-19 14:54:12 +00003146 do{
3147 newOffset = lseek(id->h, offset, SEEK_SET);
3148 SimulateIOError( newOffset-- );
3149 if( newOffset!=offset ){
3150 if( newOffset == -1 ){
3151 ((unixFile*)id)->lastErrno = errno;
3152 }else{
drhf2f105d2012-08-20 15:53:54 +00003153 ((unixFile*)id)->lastErrno = 0;
drhbd1e50c2011-08-19 14:54:12 +00003154 }
3155 return -1;
drh734c9862008-11-28 15:37:20 +00003156 }
drhbd1e50c2011-08-19 14:54:12 +00003157 got = osWrite(id->h, pBuf, cnt);
3158 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003159#endif
3160 TIMER_END;
3161 if( got<0 ){
3162 ((unixFile*)id)->lastErrno = errno;
3163 }
3164
drh308c2a52010-05-14 11:30:18 +00003165 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003166 return got;
3167}
3168
3169
3170/*
3171** Write data from a buffer into a file. Return SQLITE_OK on success
3172** or some other error code on failure.
3173*/
3174static int unixWrite(
3175 sqlite3_file *id,
3176 const void *pBuf,
3177 int amt,
3178 sqlite3_int64 offset
3179){
dan08da86a2009-08-21 17:18:03 +00003180 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003181 int wrote = 0;
3182 assert( id );
3183 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003184
dan08da86a2009-08-21 17:18:03 +00003185 /* If this is a database file (not a journal, master-journal or temp
3186 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003187#if 0
dane946c392009-08-22 11:39:46 +00003188 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003189 || offset>=PENDING_BYTE+512
3190 || offset+amt<=PENDING_BYTE
3191 );
dan7c246102010-04-12 19:00:29 +00003192#endif
drh08c6d442009-02-09 17:34:07 +00003193
drhd3d8c042012-05-29 17:02:40 +00003194#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003195 /* If we are doing a normal write to a database file (as opposed to
3196 ** doing a hot-journal rollback or a write to some file other than a
3197 ** normal database file) then record the fact that the database
3198 ** has changed. If the transaction counter is modified, record that
3199 ** fact too.
3200 */
dan08da86a2009-08-21 17:18:03 +00003201 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003202 pFile->dbUpdate = 1; /* The database has been modified */
3203 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003204 int rc;
drh8f941bc2009-01-14 23:03:40 +00003205 char oldCntr[4];
3206 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003207 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003208 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003209 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003210 pFile->transCntrChng = 1; /* The transaction counter has changed */
3211 }
3212 }
3213 }
3214#endif
3215
danf23da962013-03-23 21:00:41 +00003216 /* Deal with as much of this write request as possible by transfering
3217 ** data from the memory mapping using memcpy(). */
3218 if( offset<pFile->mmapSize ){
3219 if( offset+amt <= pFile->mmapSize ){
3220 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3221 return SQLITE_OK;
3222 }else{
3223 int nCopy = pFile->mmapSize - offset;
3224 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3225 pBuf = &((u8 *)pBuf)[nCopy];
3226 amt -= nCopy;
3227 offset += nCopy;
3228 }
3229 }
3230
dan08da86a2009-08-21 17:18:03 +00003231 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003232 amt -= wrote;
3233 offset += wrote;
3234 pBuf = &((char*)pBuf)[wrote];
3235 }
3236 SimulateIOError(( wrote=(-1), amt=1 ));
3237 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003238
drh734c9862008-11-28 15:37:20 +00003239 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003240 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003241 /* lastErrno set by seekAndWrite */
3242 return SQLITE_IOERR_WRITE;
3243 }else{
dan08da86a2009-08-21 17:18:03 +00003244 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003245 return SQLITE_FULL;
3246 }
3247 }
dan6e09d692010-07-27 18:34:15 +00003248
drh734c9862008-11-28 15:37:20 +00003249 return SQLITE_OK;
3250}
3251
3252#ifdef SQLITE_TEST
3253/*
3254** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003255** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003256*/
3257int sqlite3_sync_count = 0;
3258int sqlite3_fullsync_count = 0;
3259#endif
3260
3261/*
drh89240432009-03-25 01:06:01 +00003262** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003263** Others do no. To be safe, we will stick with the (slightly slower)
3264** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003265** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003266*/
drh20f8e132011-08-31 21:01:55 +00003267#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003268# define fdatasync fsync
3269#endif
3270
3271/*
3272** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3273** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3274** only available on Mac OS X. But that could change.
3275*/
3276#ifdef F_FULLFSYNC
3277# define HAVE_FULLFSYNC 1
3278#else
3279# define HAVE_FULLFSYNC 0
3280#endif
3281
3282
3283/*
3284** The fsync() system call does not work as advertised on many
3285** unix systems. The following procedure is an attempt to make
3286** it work better.
3287**
3288** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3289** for testing when we want to run through the test suite quickly.
3290** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3291** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3292** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003293**
3294** SQLite sets the dataOnly flag if the size of the file is unchanged.
3295** The idea behind dataOnly is that it should only write the file content
3296** to disk, not the inode. We only set dataOnly if the file size is
3297** unchanged since the file size is part of the inode. However,
3298** Ted Ts'o tells us that fdatasync() will also write the inode if the
3299** file size has changed. The only real difference between fdatasync()
3300** and fsync(), Ted tells us, is that fdatasync() will not flush the
3301** inode if the mtime or owner or other inode attributes have changed.
3302** We only care about the file size, not the other file attributes, so
3303** as far as SQLite is concerned, an fdatasync() is always adequate.
3304** So, we always use fdatasync() if it is available, regardless of
3305** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003306*/
3307static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003308 int rc;
drh734c9862008-11-28 15:37:20 +00003309
3310 /* The following "ifdef/elif/else/" block has the same structure as
3311 ** the one below. It is replicated here solely to avoid cluttering
3312 ** up the real code with the UNUSED_PARAMETER() macros.
3313 */
3314#ifdef SQLITE_NO_SYNC
3315 UNUSED_PARAMETER(fd);
3316 UNUSED_PARAMETER(fullSync);
3317 UNUSED_PARAMETER(dataOnly);
3318#elif HAVE_FULLFSYNC
3319 UNUSED_PARAMETER(dataOnly);
3320#else
3321 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003322 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003323#endif
3324
3325 /* Record the number of times that we do a normal fsync() and
3326 ** FULLSYNC. This is used during testing to verify that this procedure
3327 ** gets called with the correct arguments.
3328 */
3329#ifdef SQLITE_TEST
3330 if( fullSync ) sqlite3_fullsync_count++;
3331 sqlite3_sync_count++;
3332#endif
3333
3334 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3335 ** no-op
3336 */
3337#ifdef SQLITE_NO_SYNC
3338 rc = SQLITE_OK;
3339#elif HAVE_FULLFSYNC
3340 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003341 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003342 }else{
3343 rc = 1;
3344 }
3345 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003346 ** It shouldn't be possible for fullfsync to fail on the local
3347 ** file system (on OSX), so failure indicates that FULLFSYNC
3348 ** isn't supported for this file system. So, attempt an fsync
3349 ** and (for now) ignore the overhead of a superfluous fcntl call.
3350 ** It'd be better to detect fullfsync support once and avoid
3351 ** the fcntl call every time sync is called.
3352 */
drh734c9862008-11-28 15:37:20 +00003353 if( rc ) rc = fsync(fd);
3354
drh7ed97b92010-01-20 13:07:21 +00003355#elif defined(__APPLE__)
3356 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3357 ** so currently we default to the macro that redefines fdatasync to fsync
3358 */
3359 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003360#else
drh0b647ff2009-03-21 14:41:04 +00003361 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003362#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003363 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003364 rc = fsync(fd);
3365 }
drh0b647ff2009-03-21 14:41:04 +00003366#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003367#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3368
3369 if( OS_VXWORKS && rc!= -1 ){
3370 rc = 0;
3371 }
chw97185482008-11-17 08:05:31 +00003372 return rc;
drhbfe66312006-10-03 17:40:40 +00003373}
3374
drh734c9862008-11-28 15:37:20 +00003375/*
drh0059eae2011-08-08 23:48:40 +00003376** Open a file descriptor to the directory containing file zFilename.
3377** If successful, *pFd is set to the opened file descriptor and
3378** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3379** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3380** value.
3381**
drh90315a22011-08-10 01:52:12 +00003382** The directory file descriptor is used for only one thing - to
3383** fsync() a directory to make sure file creation and deletion events
3384** are flushed to disk. Such fsyncs are not needed on newer
3385** journaling filesystems, but are required on older filesystems.
3386**
3387** This routine can be overridden using the xSetSysCall interface.
3388** The ability to override this routine was added in support of the
3389** chromium sandbox. Opening a directory is a security risk (we are
3390** told) so making it overrideable allows the chromium sandbox to
3391** replace this routine with a harmless no-op. To make this routine
3392** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3393** *pFd set to a negative number.
3394**
drh0059eae2011-08-08 23:48:40 +00003395** If SQLITE_OK is returned, the caller is responsible for closing
3396** the file descriptor *pFd using close().
3397*/
3398static int openDirectory(const char *zFilename, int *pFd){
3399 int ii;
3400 int fd = -1;
3401 char zDirname[MAX_PATHNAME+1];
3402
3403 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3404 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3405 if( ii>0 ){
3406 zDirname[ii] = '\0';
3407 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3408 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003409 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3410 }
3411 }
3412 *pFd = fd;
3413 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3414}
3415
3416/*
drh734c9862008-11-28 15:37:20 +00003417** Make sure all writes to a particular file are committed to disk.
3418**
3419** If dataOnly==0 then both the file itself and its metadata (file
3420** size, access time, etc) are synced. If dataOnly!=0 then only the
3421** file data is synced.
3422**
3423** Under Unix, also make sure that the directory entry for the file
3424** has been created by fsync-ing the directory that contains the file.
3425** If we do not do this and we encounter a power failure, the directory
3426** entry for the journal might not exist after we reboot. The next
3427** SQLite to access the file will not know that the journal exists (because
3428** the directory entry for the journal was never created) and the transaction
3429** will not roll back - possibly leading to database corruption.
3430*/
3431static int unixSync(sqlite3_file *id, int flags){
3432 int rc;
3433 unixFile *pFile = (unixFile*)id;
3434
3435 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3436 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3437
3438 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3439 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3440 || (flags&0x0F)==SQLITE_SYNC_FULL
3441 );
3442
3443 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3444 ** line is to test that doing so does not cause any problems.
3445 */
3446 SimulateDiskfullError( return SQLITE_FULL );
3447
3448 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003449 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003450 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3451 SimulateIOError( rc=1 );
3452 if( rc ){
3453 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003454 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003455 }
drh0059eae2011-08-08 23:48:40 +00003456
3457 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003458 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3459 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003460 */
3461 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3462 int dirfd;
3463 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003464 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003465 rc = osOpenDirectory(pFile->zPath, &dirfd);
3466 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003467 full_fsync(dirfd, 0, 0);
3468 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003469 }else if( rc==SQLITE_CANTOPEN ){
3470 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003471 }
drh0059eae2011-08-08 23:48:40 +00003472 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003473 }
3474 return rc;
3475}
3476
3477/*
3478** Truncate an open file to a specified size
3479*/
3480static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003481 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003482 int rc;
dan6e09d692010-07-27 18:34:15 +00003483 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003484 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003485
3486 /* If the user has configured a chunk-size for this file, truncate the
3487 ** file so that it consists of an integer number of chunks (i.e. the
3488 ** actual file size after the operation may be larger than the requested
3489 ** size).
3490 */
drhb8af4b72012-04-05 20:04:39 +00003491 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003492 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3493 }
3494
drhff812312011-02-23 13:33:46 +00003495 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003496 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003497 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003498 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003499 }else{
drhd3d8c042012-05-29 17:02:40 +00003500#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003501 /* If we are doing a normal write to a database file (as opposed to
3502 ** doing a hot-journal rollback or a write to some file other than a
3503 ** normal database file) and we truncate the file to zero length,
3504 ** that effectively updates the change counter. This might happen
3505 ** when restoring a database using the backup API from a zero-length
3506 ** source.
3507 */
dan6e09d692010-07-27 18:34:15 +00003508 if( pFile->inNormalWrite && nByte==0 ){
3509 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003510 }
danf23da962013-03-23 21:00:41 +00003511#endif
danc0003312013-03-22 17:46:11 +00003512
3513 /* If the file was just truncated to a size smaller than the currently
3514 ** mapped region, reduce the effective mapping size as well. SQLite will
3515 ** use read() and write() to access data beyond this point from now on.
3516 */
3517 if( nByte<pFile->mmapSize ){
3518 pFile->mmapSize = nByte;
3519 }
drh3313b142009-11-06 04:13:18 +00003520
drh734c9862008-11-28 15:37:20 +00003521 return SQLITE_OK;
3522 }
3523}
3524
3525/*
3526** Determine the current size of a file in bytes
3527*/
3528static int unixFileSize(sqlite3_file *id, i64 *pSize){
3529 int rc;
3530 struct stat buf;
3531 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003532 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003533 SimulateIOError( rc=1 );
3534 if( rc!=0 ){
3535 ((unixFile*)id)->lastErrno = errno;
3536 return SQLITE_IOERR_FSTAT;
3537 }
3538 *pSize = buf.st_size;
3539
drh8af6c222010-05-14 12:43:01 +00003540 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003541 ** writes a single byte into that file in order to work around a bug
3542 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3543 ** layers, we need to report this file size as zero even though it is
3544 ** really 1. Ticket #3260.
3545 */
3546 if( *pSize==1 ) *pSize = 0;
3547
3548
3549 return SQLITE_OK;
3550}
3551
drhd2cb50b2009-01-09 21:41:17 +00003552#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003553/*
3554** Handler for proxy-locking file-control verbs. Defined below in the
3555** proxying locking division.
3556*/
3557static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003558#endif
drh715ff302008-12-03 22:32:44 +00003559
dan502019c2010-07-28 14:26:17 +00003560/*
3561** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003562** file-control operation. Enlarge the database to nBytes in size
3563** (rounded up to the next chunk-size). If the database is already
3564** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003565*/
3566static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003567 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003568 i64 nSize; /* Required file size */
3569 struct stat buf; /* Used to hold return values of fstat() */
3570
drh99ab3b12011-03-02 15:09:07 +00003571 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003572
3573 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3574 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003575
dan502019c2010-07-28 14:26:17 +00003576#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003577 /* The code below is handling the return value of osFallocate()
3578 ** correctly. posix_fallocate() is defined to "returns zero on success,
3579 ** or an error number on failure". See the manpage for details. */
3580 int err;
drhff812312011-02-23 13:33:46 +00003581 do{
dan661d71a2011-03-30 19:08:03 +00003582 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3583 }while( err==EINTR );
3584 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003585#else
3586 /* If the OS does not have posix_fallocate(), fake it. First use
3587 ** ftruncate() to set the file size, then write a single byte to
3588 ** the last byte in each block within the extended region. This
3589 ** is the same technique used by glibc to implement posix_fallocate()
3590 ** on systems that do not have a real fallocate() system call.
3591 */
3592 int nBlk = buf.st_blksize; /* File-system block size */
3593 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003594
drhff812312011-02-23 13:33:46 +00003595 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003596 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003597 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003598 }
3599 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003600 while( iWrite<nSize ){
3601 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3602 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003603 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003604 }
dan502019c2010-07-28 14:26:17 +00003605#endif
3606 }
3607 }
3608
danf23da962013-03-23 21:00:41 +00003609 if( pFile->mmapLimit>0 ){
3610 int rc;
3611 if( pFile->szChunk<=0 ){
3612 if( robust_ftruncate(pFile->h, nByte) ){
3613 pFile->lastErrno = errno;
3614 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3615 }
3616 }
3617
3618 rc = unixMapfile(pFile, nByte);
3619 return rc;
3620 }
3621
dan502019c2010-07-28 14:26:17 +00003622 return SQLITE_OK;
3623}
danielk1977ad94b582007-08-20 06:44:22 +00003624
danielk1977e3026632004-06-22 11:29:02 +00003625/*
drhf12b3f62011-12-21 14:42:29 +00003626** If *pArg is inititially negative then this is a query. Set *pArg to
3627** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3628**
3629** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3630*/
3631static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3632 if( *pArg<0 ){
3633 *pArg = (pFile->ctrlFlags & mask)!=0;
3634 }else if( (*pArg)==0 ){
3635 pFile->ctrlFlags &= ~mask;
3636 }else{
3637 pFile->ctrlFlags |= mask;
3638 }
3639}
3640
drh696b33e2012-12-06 19:01:42 +00003641/* Forward declaration */
3642static int unixGetTempname(int nBuf, char *zBuf);
3643
drhf12b3f62011-12-21 14:42:29 +00003644/*
drh9e33c2c2007-08-31 18:34:59 +00003645** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003646*/
drhcc6bb3e2007-08-31 16:11:35 +00003647static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003648 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003649 switch( op ){
3650 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003651 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003652 return SQLITE_OK;
3653 }
drh7708e972008-11-29 00:56:52 +00003654 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003655 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003656 return SQLITE_OK;
3657 }
dan6e09d692010-07-27 18:34:15 +00003658 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003659 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003660 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003661 }
drh9ff27ec2010-05-19 19:26:05 +00003662 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003663 int rc;
3664 SimulateIOErrorBenign(1);
3665 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3666 SimulateIOErrorBenign(0);
3667 return rc;
drhf0b190d2011-07-26 16:03:07 +00003668 }
3669 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003670 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3671 return SQLITE_OK;
3672 }
drhcb15f352011-12-23 01:04:17 +00003673 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3674 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003675 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003676 }
drhde60fc22011-12-14 17:53:36 +00003677 case SQLITE_FCNTL_VFSNAME: {
3678 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3679 return SQLITE_OK;
3680 }
drh696b33e2012-12-06 19:01:42 +00003681 case SQLITE_FCNTL_TEMPFILENAME: {
3682 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3683 if( zTFile ){
3684 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3685 *(char**)pArg = zTFile;
3686 }
3687 return SQLITE_OK;
3688 }
danf23da962013-03-23 21:00:41 +00003689 case SQLITE_FCNTL_MMAP_SIZE: {
3690 pFile->mmapLimit = *(i64*)pArg;
danb2d3de32013-03-14 18:34:37 +00003691 return SQLITE_OK;
3692 }
drhd3d8c042012-05-29 17:02:40 +00003693#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003694 /* The pager calls this method to signal that it has done
3695 ** a rollback and that the database is therefore unchanged and
3696 ** it hence it is OK for the transaction change counter to be
3697 ** unchanged.
3698 */
3699 case SQLITE_FCNTL_DB_UNCHANGED: {
3700 ((unixFile*)id)->dbUpdate = 0;
3701 return SQLITE_OK;
3702 }
3703#endif
drhd2cb50b2009-01-09 21:41:17 +00003704#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003705 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003706 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003707 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003708 }
drhd2cb50b2009-01-09 21:41:17 +00003709#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003710 }
drh0b52b7d2011-01-26 19:46:22 +00003711 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003712}
3713
3714/*
danielk1977a3d4c882007-03-23 10:08:38 +00003715** Return the sector size in bytes of the underlying block device for
3716** the specified file. This is almost always 512 bytes, but may be
3717** larger for some devices.
3718**
3719** SQLite code assumes this function cannot fail. It also assumes that
3720** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003721** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003722** same for both.
3723*/
drh537dddf2012-10-26 13:46:24 +00003724#ifndef __QNXNTO__
3725static int unixSectorSize(sqlite3_file *NotUsed){
3726 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003727 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003728}
drh537dddf2012-10-26 13:46:24 +00003729#endif
3730
3731/*
3732** The following version of unixSectorSize() is optimized for QNX.
3733*/
3734#ifdef __QNXNTO__
3735#include <sys/dcmd_blk.h>
3736#include <sys/statvfs.h>
3737static int unixSectorSize(sqlite3_file *id){
3738 unixFile *pFile = (unixFile*)id;
3739 if( pFile->sectorSize == 0 ){
3740 struct statvfs fsInfo;
3741
3742 /* Set defaults for non-supported filesystems */
3743 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3744 pFile->deviceCharacteristics = 0;
3745 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3746 return pFile->sectorSize;
3747 }
3748
3749 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3750 pFile->sectorSize = fsInfo.f_bsize;
3751 pFile->deviceCharacteristics =
3752 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3753 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3754 ** the write succeeds */
3755 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3756 ** so it is ordered */
3757 0;
3758 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3759 pFile->sectorSize = fsInfo.f_bsize;
3760 pFile->deviceCharacteristics =
3761 /* etfs cluster size writes are atomic */
3762 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3763 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3764 ** the write succeeds */
3765 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3766 ** so it is ordered */
3767 0;
3768 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3769 pFile->sectorSize = fsInfo.f_bsize;
3770 pFile->deviceCharacteristics =
3771 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3772 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3773 ** the write succeeds */
3774 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3775 ** so it is ordered */
3776 0;
3777 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3778 pFile->sectorSize = fsInfo.f_bsize;
3779 pFile->deviceCharacteristics =
3780 /* full bitset of atomics from max sector size and smaller */
3781 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3782 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3783 ** so it is ordered */
3784 0;
3785 }else if( strstr(fsInfo.f_basetype, "dos") ){
3786 pFile->sectorSize = fsInfo.f_bsize;
3787 pFile->deviceCharacteristics =
3788 /* full bitset of atomics from max sector size and smaller */
3789 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3790 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3791 ** so it is ordered */
3792 0;
3793 }else{
3794 pFile->deviceCharacteristics =
3795 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3796 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3797 ** the write succeeds */
3798 0;
3799 }
3800 }
3801 /* Last chance verification. If the sector size isn't a multiple of 512
3802 ** then it isn't valid.*/
3803 if( pFile->sectorSize % 512 != 0 ){
3804 pFile->deviceCharacteristics = 0;
3805 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3806 }
3807 return pFile->sectorSize;
3808}
3809#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003810
danielk197790949c22007-08-17 16:50:38 +00003811/*
drhf12b3f62011-12-21 14:42:29 +00003812** Return the device characteristics for the file.
3813**
drhcb15f352011-12-23 01:04:17 +00003814** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3815** However, that choice is contraversial since technically the underlying
3816** file system does not always provide powersafe overwrites. (In other
3817** words, after a power-loss event, parts of the file that were never
3818** written might end up being altered.) However, non-PSOW behavior is very,
3819** very rare. And asserting PSOW makes a large reduction in the amount
3820** of required I/O for journaling, since a lot of padding is eliminated.
3821** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3822** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003823*/
drhf12b3f62011-12-21 14:42:29 +00003824static int unixDeviceCharacteristics(sqlite3_file *id){
3825 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003826 int rc = 0;
3827#ifdef __QNXNTO__
3828 if( p->sectorSize==0 ) unixSectorSize(id);
3829 rc = p->deviceCharacteristics;
3830#endif
drhcb15f352011-12-23 01:04:17 +00003831 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003832 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003833 }
drh537dddf2012-10-26 13:46:24 +00003834 return rc;
danielk197762079062007-08-15 17:08:46 +00003835}
3836
drhd9e5c4f2010-05-12 18:01:39 +00003837#ifndef SQLITE_OMIT_WAL
3838
3839
3840/*
drhd91c68f2010-05-14 14:52:25 +00003841** Object used to represent an shared memory buffer.
3842**
3843** When multiple threads all reference the same wal-index, each thread
3844** has its own unixShm object, but they all point to a single instance
3845** of this unixShmNode object. In other words, each wal-index is opened
3846** only once per process.
3847**
3848** Each unixShmNode object is connected to a single unixInodeInfo object.
3849** We could coalesce this object into unixInodeInfo, but that would mean
3850** every open file that does not use shared memory (in other words, most
3851** open files) would have to carry around this extra information. So
3852** the unixInodeInfo object contains a pointer to this unixShmNode object
3853** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003854**
3855** unixMutexHeld() must be true when creating or destroying
3856** this object or while reading or writing the following fields:
3857**
3858** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003859**
3860** The following fields are read-only after the object is created:
3861**
3862** fid
3863** zFilename
3864**
drhd91c68f2010-05-14 14:52:25 +00003865** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003866** unixMutexHeld() is true when reading or writing any other field
3867** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003868*/
drhd91c68f2010-05-14 14:52:25 +00003869struct unixShmNode {
3870 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003871 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003872 char *zFilename; /* Name of the mmapped file */
3873 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003874 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003875 u16 nRegion; /* Size of array apRegion */
3876 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003877 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003878 int nRef; /* Number of unixShm objects pointing to this */
3879 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003880#ifdef SQLITE_DEBUG
3881 u8 exclMask; /* Mask of exclusive locks held */
3882 u8 sharedMask; /* Mask of shared locks held */
3883 u8 nextShmId; /* Next available unixShm.id value */
3884#endif
3885};
3886
3887/*
drhd9e5c4f2010-05-12 18:01:39 +00003888** Structure used internally by this VFS to record the state of an
3889** open shared memory connection.
3890**
drhd91c68f2010-05-14 14:52:25 +00003891** The following fields are initialized when this object is created and
3892** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003893**
drhd91c68f2010-05-14 14:52:25 +00003894** unixShm.pFile
3895** unixShm.id
3896**
3897** All other fields are read/write. The unixShm.pFile->mutex must be held
3898** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003899*/
3900struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003901 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3902 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003903 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003904 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003905 u16 sharedMask; /* Mask of shared locks held */
3906 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003907};
3908
3909/*
drhd9e5c4f2010-05-12 18:01:39 +00003910** Constants used for locking
3911*/
drhbd9676c2010-06-23 17:58:38 +00003912#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003913#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003914
drhd9e5c4f2010-05-12 18:01:39 +00003915/*
drh73b64e42010-05-30 19:55:15 +00003916** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003917**
3918** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3919** otherwise.
3920*/
3921static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003922 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3923 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003924 int ofst, /* First byte of the locking range */
3925 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003926){
3927 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003928 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003929
drhd91c68f2010-05-14 14:52:25 +00003930 /* Access to the unixShmNode object is serialized by the caller */
3931 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003932
drh73b64e42010-05-30 19:55:15 +00003933 /* Shared locks never span more than one byte */
3934 assert( n==1 || lockType!=F_RDLCK );
3935
3936 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003937 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003938
drh3cb93392011-03-12 18:10:44 +00003939 if( pShmNode->h>=0 ){
3940 /* Initialize the locking parameters */
3941 memset(&f, 0, sizeof(f));
3942 f.l_type = lockType;
3943 f.l_whence = SEEK_SET;
3944 f.l_start = ofst;
3945 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003946
drh3cb93392011-03-12 18:10:44 +00003947 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3948 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3949 }
drhd9e5c4f2010-05-12 18:01:39 +00003950
3951 /* Update the global lock state and do debug tracing */
3952#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003953 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003954 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003955 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003956 if( rc==SQLITE_OK ){
3957 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003958 OSTRACE(("unlock %d ok", ofst));
3959 pShmNode->exclMask &= ~mask;
3960 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003961 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003962 OSTRACE(("read-lock %d ok", ofst));
3963 pShmNode->exclMask &= ~mask;
3964 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003965 }else{
3966 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003967 OSTRACE(("write-lock %d ok", ofst));
3968 pShmNode->exclMask |= mask;
3969 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003970 }
3971 }else{
3972 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003973 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003974 }else if( lockType==F_RDLCK ){
3975 OSTRACE(("read-lock failed"));
3976 }else{
3977 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003978 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003979 }
3980 }
drh20e1f082010-05-31 16:10:12 +00003981 OSTRACE((" - afterwards %03x,%03x\n",
3982 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003983 }
drhd9e5c4f2010-05-12 18:01:39 +00003984#endif
3985
3986 return rc;
3987}
3988
drhd9e5c4f2010-05-12 18:01:39 +00003989
3990/*
drhd91c68f2010-05-14 14:52:25 +00003991** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003992**
3993** This is not a VFS shared-memory method; it is a utility function called
3994** by VFS shared-memory methods.
3995*/
drhd91c68f2010-05-14 14:52:25 +00003996static void unixShmPurge(unixFile *pFd){
3997 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003998 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003999 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004000 int i;
drhd91c68f2010-05-14 14:52:25 +00004001 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004002 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004003 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004004 if( p->h>=0 ){
4005 munmap(p->apRegion[i], p->szRegion);
4006 }else{
4007 sqlite3_free(p->apRegion[i]);
4008 }
dan13a3cb82010-06-11 19:04:21 +00004009 }
dan18801912010-06-14 14:07:50 +00004010 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004011 if( p->h>=0 ){
4012 robust_close(pFd, p->h, __LINE__);
4013 p->h = -1;
4014 }
drhd91c68f2010-05-14 14:52:25 +00004015 p->pInode->pShmNode = 0;
4016 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004017 }
4018}
4019
4020/*
danda9fe0c2010-07-13 18:44:03 +00004021** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004022** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004023**
drh7234c6d2010-06-19 15:10:09 +00004024** The file used to implement shared-memory is in the same directory
4025** as the open database file and has the same name as the open database
4026** file with the "-shm" suffix added. For example, if the database file
4027** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004028** for shared memory will be called "/home/user1/config.db-shm".
4029**
4030** Another approach to is to use files in /dev/shm or /dev/tmp or an
4031** some other tmpfs mount. But if a file in a different directory
4032** from the database file is used, then differing access permissions
4033** or a chroot() might cause two different processes on the same
4034** database to end up using different files for shared memory -
4035** meaning that their memory would not really be shared - resulting
4036** in database corruption. Nevertheless, this tmpfs file usage
4037** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4038** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4039** option results in an incompatible build of SQLite; builds of SQLite
4040** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4041** same database file at the same time, database corruption will likely
4042** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4043** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004044**
4045** When opening a new shared-memory file, if no other instances of that
4046** file are currently open, in this process or in other processes, then
4047** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004048**
4049** If the original database file (pDbFd) is using the "unix-excl" VFS
4050** that means that an exclusive lock is held on the database file and
4051** that no other processes are able to read or write the database. In
4052** that case, we do not really need shared memory. No shared memory
4053** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004054*/
danda9fe0c2010-07-13 18:44:03 +00004055static int unixOpenSharedMemory(unixFile *pDbFd){
4056 struct unixShm *p = 0; /* The connection to be opened */
4057 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4058 int rc; /* Result code */
4059 unixInodeInfo *pInode; /* The inode of fd */
4060 char *zShmFilename; /* Name of the file used for SHM */
4061 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004062
danda9fe0c2010-07-13 18:44:03 +00004063 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004064 p = sqlite3_malloc( sizeof(*p) );
4065 if( p==0 ) return SQLITE_NOMEM;
4066 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004067 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004068
danda9fe0c2010-07-13 18:44:03 +00004069 /* Check to see if a unixShmNode object already exists. Reuse an existing
4070 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004071 */
4072 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004073 pInode = pDbFd->pInode;
4074 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004075 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004076 struct stat sStat; /* fstat() info for database file */
4077
4078 /* Call fstat() to figure out the permissions on the database file. If
4079 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004080 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004081 */
drh3cb93392011-03-12 18:10:44 +00004082 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004083 rc = SQLITE_IOERR_FSTAT;
4084 goto shm_open_err;
4085 }
4086
drha4ced192010-07-15 18:32:40 +00004087#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004088 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004089#else
drh52bcde02012-01-03 14:50:45 +00004090 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004091#endif
drh7234c6d2010-06-19 15:10:09 +00004092 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004093 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004094 rc = SQLITE_NOMEM;
4095 goto shm_open_err;
4096 }
drh9cb5a0d2012-01-05 21:19:54 +00004097 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004098 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004099#ifdef SQLITE_SHM_DIRECTORY
4100 sqlite3_snprintf(nShmFilename, zShmFilename,
4101 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4102 (u32)sStat.st_ino, (u32)sStat.st_dev);
4103#else
drh7234c6d2010-06-19 15:10:09 +00004104 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004105 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004106#endif
drhd91c68f2010-05-14 14:52:25 +00004107 pShmNode->h = -1;
4108 pDbFd->pInode->pShmNode = pShmNode;
4109 pShmNode->pInode = pDbFd->pInode;
4110 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4111 if( pShmNode->mutex==0 ){
4112 rc = SQLITE_NOMEM;
4113 goto shm_open_err;
4114 }
drhd9e5c4f2010-05-12 18:01:39 +00004115
drh3cb93392011-03-12 18:10:44 +00004116 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004117 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004118 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004119 openFlags = O_RDONLY;
4120 pShmNode->isReadonly = 1;
4121 }
4122 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004123 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004124 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4125 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004126 }
drhac7c3ac2012-02-11 19:23:48 +00004127
4128 /* If this process is running as root, make sure that the SHM file
4129 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004130 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004131 */
drhed466822012-05-31 13:10:49 +00004132 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004133
4134 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004135 ** If not, truncate the file to zero length.
4136 */
4137 rc = SQLITE_OK;
4138 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4139 if( robust_ftruncate(pShmNode->h, 0) ){
4140 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004141 }
4142 }
drh66dfec8b2011-06-01 20:01:49 +00004143 if( rc==SQLITE_OK ){
4144 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4145 }
4146 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004147 }
drhd9e5c4f2010-05-12 18:01:39 +00004148 }
4149
drhd91c68f2010-05-14 14:52:25 +00004150 /* Make the new connection a child of the unixShmNode */
4151 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004152#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004153 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004154#endif
drhd91c68f2010-05-14 14:52:25 +00004155 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004156 pDbFd->pShm = p;
4157 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004158
4159 /* The reference count on pShmNode has already been incremented under
4160 ** the cover of the unixEnterMutex() mutex and the pointer from the
4161 ** new (struct unixShm) object to the pShmNode has been set. All that is
4162 ** left to do is to link the new object into the linked list starting
4163 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4164 ** mutex.
4165 */
4166 sqlite3_mutex_enter(pShmNode->mutex);
4167 p->pNext = pShmNode->pFirst;
4168 pShmNode->pFirst = p;
4169 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004170 return SQLITE_OK;
4171
4172 /* Jump here on any error */
4173shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004174 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004175 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004176 unixLeaveMutex();
4177 return rc;
4178}
4179
4180/*
danda9fe0c2010-07-13 18:44:03 +00004181** This function is called to obtain a pointer to region iRegion of the
4182** shared-memory associated with the database file fd. Shared-memory regions
4183** are numbered starting from zero. Each shared-memory region is szRegion
4184** bytes in size.
4185**
4186** If an error occurs, an error code is returned and *pp is set to NULL.
4187**
4188** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4189** region has not been allocated (by any client, including one running in a
4190** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4191** bExtend is non-zero and the requested shared-memory region has not yet
4192** been allocated, it is allocated by this function.
4193**
4194** If the shared-memory region has already been allocated or is allocated by
4195** this call as described above, then it is mapped into this processes
4196** address space (if it is not already), *pp is set to point to the mapped
4197** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004198*/
danda9fe0c2010-07-13 18:44:03 +00004199static int unixShmMap(
4200 sqlite3_file *fd, /* Handle open on database file */
4201 int iRegion, /* Region to retrieve */
4202 int szRegion, /* Size of regions */
4203 int bExtend, /* True to extend file if necessary */
4204 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004205){
danda9fe0c2010-07-13 18:44:03 +00004206 unixFile *pDbFd = (unixFile*)fd;
4207 unixShm *p;
4208 unixShmNode *pShmNode;
4209 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004210
danda9fe0c2010-07-13 18:44:03 +00004211 /* If the shared-memory file has not yet been opened, open it now. */
4212 if( pDbFd->pShm==0 ){
4213 rc = unixOpenSharedMemory(pDbFd);
4214 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004215 }
drhd9e5c4f2010-05-12 18:01:39 +00004216
danda9fe0c2010-07-13 18:44:03 +00004217 p = pDbFd->pShm;
4218 pShmNode = p->pShmNode;
4219 sqlite3_mutex_enter(pShmNode->mutex);
4220 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004221 assert( pShmNode->pInode==pDbFd->pInode );
4222 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4223 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004224
4225 if( pShmNode->nRegion<=iRegion ){
4226 char **apNew; /* New apRegion[] array */
4227 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4228 struct stat sStat; /* Used by fstat() */
4229
4230 pShmNode->szRegion = szRegion;
4231
drh3cb93392011-03-12 18:10:44 +00004232 if( pShmNode->h>=0 ){
4233 /* The requested region is not mapped into this processes address space.
4234 ** Check to see if it has been allocated (i.e. if the wal-index file is
4235 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004236 */
drh3cb93392011-03-12 18:10:44 +00004237 if( osFstat(pShmNode->h, &sStat) ){
4238 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004239 goto shmpage_out;
4240 }
drh3cb93392011-03-12 18:10:44 +00004241
4242 if( sStat.st_size<nByte ){
4243 /* The requested memory region does not exist. If bExtend is set to
4244 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4245 **
4246 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4247 ** the requested memory region.
4248 */
4249 if( !bExtend ) goto shmpage_out;
drh0fbb50e2012-11-13 10:54:12 +00004250#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
4251 if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
4252 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
4253 pShmNode->zFilename);
4254 goto shmpage_out;
4255 }
4256#else
drh3cb93392011-03-12 18:10:44 +00004257 if( robust_ftruncate(pShmNode->h, nByte) ){
4258 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4259 pShmNode->zFilename);
4260 goto shmpage_out;
4261 }
drh0fbb50e2012-11-13 10:54:12 +00004262#endif
drh3cb93392011-03-12 18:10:44 +00004263 }
danda9fe0c2010-07-13 18:44:03 +00004264 }
4265
4266 /* Map the requested memory region into this processes address space. */
4267 apNew = (char **)sqlite3_realloc(
4268 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4269 );
4270 if( !apNew ){
4271 rc = SQLITE_IOERR_NOMEM;
4272 goto shmpage_out;
4273 }
4274 pShmNode->apRegion = apNew;
4275 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004276 void *pMem;
4277 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004278 pMem = mmap(0, szRegion,
4279 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004280 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004281 );
4282 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004283 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004284 goto shmpage_out;
4285 }
4286 }else{
4287 pMem = sqlite3_malloc(szRegion);
4288 if( pMem==0 ){
4289 rc = SQLITE_NOMEM;
4290 goto shmpage_out;
4291 }
4292 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004293 }
4294 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4295 pShmNode->nRegion++;
4296 }
4297 }
4298
4299shmpage_out:
4300 if( pShmNode->nRegion>iRegion ){
4301 *pp = pShmNode->apRegion[iRegion];
4302 }else{
4303 *pp = 0;
4304 }
drh66dfec8b2011-06-01 20:01:49 +00004305 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004306 sqlite3_mutex_leave(pShmNode->mutex);
4307 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004308}
4309
4310/*
drhd9e5c4f2010-05-12 18:01:39 +00004311** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004312**
4313** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4314** different here than in posix. In xShmLock(), one can go from unlocked
4315** to shared and back or from unlocked to exclusive and back. But one may
4316** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004317*/
4318static int unixShmLock(
4319 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004320 int ofst, /* First lock to acquire or release */
4321 int n, /* Number of locks to acquire or release */
4322 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004323){
drh73b64e42010-05-30 19:55:15 +00004324 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4325 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4326 unixShm *pX; /* For looping over all siblings */
4327 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4328 int rc = SQLITE_OK; /* Result code */
4329 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004330
drhd91c68f2010-05-14 14:52:25 +00004331 assert( pShmNode==pDbFd->pInode->pShmNode );
4332 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004333 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004334 assert( n>=1 );
4335 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4336 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4337 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4338 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4339 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004340 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4341 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004342
drhc99597c2010-05-31 01:41:15 +00004343 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004344 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004345 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004346 if( flags & SQLITE_SHM_UNLOCK ){
4347 u16 allMask = 0; /* Mask of locks held by siblings */
4348
4349 /* See if any siblings hold this same lock */
4350 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4351 if( pX==p ) continue;
4352 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4353 allMask |= pX->sharedMask;
4354 }
4355
4356 /* Unlock the system-level locks */
4357 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004358 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004359 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004360 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004361 }
drh73b64e42010-05-30 19:55:15 +00004362
4363 /* Undo the local locks */
4364 if( rc==SQLITE_OK ){
4365 p->exclMask &= ~mask;
4366 p->sharedMask &= ~mask;
4367 }
4368 }else if( flags & SQLITE_SHM_SHARED ){
4369 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4370
4371 /* Find out which shared locks are already held by sibling connections.
4372 ** If any sibling already holds an exclusive lock, go ahead and return
4373 ** SQLITE_BUSY.
4374 */
4375 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004376 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004377 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004378 break;
4379 }
4380 allShared |= pX->sharedMask;
4381 }
4382
4383 /* Get shared locks at the system level, if necessary */
4384 if( rc==SQLITE_OK ){
4385 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004386 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004387 }else{
drh73b64e42010-05-30 19:55:15 +00004388 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004389 }
drhd9e5c4f2010-05-12 18:01:39 +00004390 }
drh73b64e42010-05-30 19:55:15 +00004391
4392 /* Get the local shared locks */
4393 if( rc==SQLITE_OK ){
4394 p->sharedMask |= mask;
4395 }
4396 }else{
4397 /* Make sure no sibling connections hold locks that will block this
4398 ** lock. If any do, return SQLITE_BUSY right away.
4399 */
4400 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004401 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4402 rc = SQLITE_BUSY;
4403 break;
4404 }
4405 }
4406
4407 /* Get the exclusive locks at the system level. Then if successful
4408 ** also mark the local connection as being locked.
4409 */
4410 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004411 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004412 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004413 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004414 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004415 }
drhd9e5c4f2010-05-12 18:01:39 +00004416 }
4417 }
drhd91c68f2010-05-14 14:52:25 +00004418 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004419 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4420 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004421 return rc;
4422}
4423
drh286a2882010-05-20 23:51:06 +00004424/*
4425** Implement a memory barrier or memory fence on shared memory.
4426**
4427** All loads and stores begun before the barrier must complete before
4428** any load or store begun after the barrier.
4429*/
4430static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004431 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004432){
drhff828942010-06-26 21:34:06 +00004433 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004434 unixEnterMutex();
4435 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004436}
4437
dan18801912010-06-14 14:07:50 +00004438/*
danda9fe0c2010-07-13 18:44:03 +00004439** Close a connection to shared-memory. Delete the underlying
4440** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004441**
4442** If there is no shared memory associated with the connection then this
4443** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004444*/
danda9fe0c2010-07-13 18:44:03 +00004445static int unixShmUnmap(
4446 sqlite3_file *fd, /* The underlying database file */
4447 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004448){
danda9fe0c2010-07-13 18:44:03 +00004449 unixShm *p; /* The connection to be closed */
4450 unixShmNode *pShmNode; /* The underlying shared-memory file */
4451 unixShm **pp; /* For looping over sibling connections */
4452 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004453
danda9fe0c2010-07-13 18:44:03 +00004454 pDbFd = (unixFile*)fd;
4455 p = pDbFd->pShm;
4456 if( p==0 ) return SQLITE_OK;
4457 pShmNode = p->pShmNode;
4458
4459 assert( pShmNode==pDbFd->pInode->pShmNode );
4460 assert( pShmNode->pInode==pDbFd->pInode );
4461
4462 /* Remove connection p from the set of connections associated
4463 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004464 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004465 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4466 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004467
danda9fe0c2010-07-13 18:44:03 +00004468 /* Free the connection p */
4469 sqlite3_free(p);
4470 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004471 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004472
4473 /* If pShmNode->nRef has reached 0, then close the underlying
4474 ** shared-memory file, too */
4475 unixEnterMutex();
4476 assert( pShmNode->nRef>0 );
4477 pShmNode->nRef--;
4478 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004479 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004480 unixShmPurge(pDbFd);
4481 }
4482 unixLeaveMutex();
4483
4484 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004485}
drh286a2882010-05-20 23:51:06 +00004486
danda9fe0c2010-07-13 18:44:03 +00004487
drhd9e5c4f2010-05-12 18:01:39 +00004488#else
drh6b017cc2010-06-14 18:01:46 +00004489# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004490# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004491# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004492# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004493#endif /* #ifndef SQLITE_OMIT_WAL */
4494
drh734c9862008-11-28 15:37:20 +00004495/*
danaef49d72013-03-25 16:28:54 +00004496** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004497*/
danf23da962013-03-23 21:00:41 +00004498static void unixUnmapfile(unixFile *pFd){
4499 assert( pFd->nFetchOut==0 );
4500 if( pFd->pMapRegion ){
4501 munmap(pFd->pMapRegion, pFd->mmapOrigsize);
4502 pFd->pMapRegion = 0;
4503 pFd->mmapSize = 0;
4504 pFd->mmapOrigsize = 0;
4505 }
4506}
dan5d8a1372013-03-19 19:28:06 +00004507
danaef49d72013-03-25 16:28:54 +00004508/*
4509** Memory map or remap the file opened by file-descriptor pFd (if the file
4510** is already mapped, the existing mapping is replaced by the new). Or, if
4511** there already exists a mapping for this file, and there are still
4512** outstanding xFetch() references to it, this function is a no-op.
4513**
4514** If parameter nByte is non-negative, then it is the requested size of
4515** the mapping to create. Otherwise, if nByte is less than zero, then the
4516** requested size is the size of the file on disk. The actual size of the
4517** created mapping is either the requested size or the value configured
4518** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
4519**
4520** SQLITE_OK is returned if no error occurs (even if the mapping is not
4521** recreated as a result of outstanding references) or an SQLite error
4522** code otherwise.
4523*/
danf23da962013-03-23 21:00:41 +00004524static int unixMapfile(unixFile *pFd, i64 nByte){
4525 i64 nMap = nByte;
4526 int rc;
daneb97b292013-03-20 14:26:59 +00004527
danf23da962013-03-23 21:00:41 +00004528 assert( nMap>=0 || pFd->nFetchOut==0 );
4529 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4530
4531 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004532 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004533 rc = osFstat(pFd->h, &statbuf);
4534 if( rc!=SQLITE_OK ){
4535 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004536 }
danf23da962013-03-23 21:00:41 +00004537 nMap = statbuf.st_size;
4538 }
4539 if( nMap>pFd->mmapLimit ){
4540 nMap = pFd->mmapLimit;
daneb97b292013-03-20 14:26:59 +00004541 }
4542
danf23da962013-03-23 21:00:41 +00004543 if( nMap!=pFd->mmapSize ){
danf23da962013-03-23 21:00:41 +00004544 unixUnmapfile(pFd);
dand306e1a2013-03-20 18:25:49 +00004545
danf23da962013-03-23 21:00:41 +00004546 if( nMap>0 ){
4547 void *pNew;
4548 int flags = PROT_READ;
4549 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danaef49d72013-03-25 16:28:54 +00004550 pNew = mmap(0, nMap, flags, MAP_SHARED, pFd->h, 0);
danf23da962013-03-23 21:00:41 +00004551 if( pNew==MAP_FAILED ){
danaef49d72013-03-25 16:28:54 +00004552 return SQLITE_IOERR_MMAP;
danf23da962013-03-23 21:00:41 +00004553 }
dand306e1a2013-03-20 18:25:49 +00004554
danf23da962013-03-23 21:00:41 +00004555 pFd->pMapRegion = pNew;
danaef49d72013-03-25 16:28:54 +00004556 pFd->mmapSize = nMap;
4557 pFd->mmapOrigsize = nMap;
dan5d8a1372013-03-19 19:28:06 +00004558 }
4559 }
4560
danf23da962013-03-23 21:00:41 +00004561 return SQLITE_OK;
4562}
4563
danaef49d72013-03-25 16:28:54 +00004564/*
4565** If possible, return a pointer to a mapping of file fd starting at offset
4566** iOff. The mapping must be valid for at least nAmt bytes.
4567**
4568** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4569** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4570** Finally, if an error does occur, return an SQLite error code. The final
4571** value of *pp is undefined in this case.
4572**
4573** If this function does return a pointer, the caller must eventually
4574** release the reference by calling unixUnfetch().
4575*/
danf23da962013-03-23 21:00:41 +00004576static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
4577 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4578 *pp = 0;
4579
4580 if( pFd->mmapLimit>0 ){
4581 if( pFd->pMapRegion==0 ){
4582 int rc = unixMapfile(pFd, -1);
4583 if( rc!=SQLITE_OK ) return rc;
4584 }
4585 if( pFd->mmapSize >= iOff+nAmt ){
4586 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4587 pFd->nFetchOut++;
4588 }
4589 }
4590 return SQLITE_OK;
4591}
4592
danaef49d72013-03-25 16:28:54 +00004593/*
4594** If the second argument is non-NULL, then this function releases a
4595** reference obtained by an earlier call to unixFetch(). Or, if the second
4596** argument is NULL, then this function is being called to inform the VFS
4597** layer that, according to POSIX, any existing mapping may now be invalid
4598** and should be unmapped.
4599*/
danf23da962013-03-23 21:00:41 +00004600static int unixUnfetch(sqlite3_file *fd, void *p){
4601 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4602
danaef49d72013-03-25 16:28:54 +00004603 /* If p==0 (unmap the entire file) then there must be no outstanding
4604 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4605 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004606 assert( (p==0)==(pFd->nFetchOut==0) );
4607
4608 if( p ){
4609 pFd->nFetchOut--;
4610 }else{
4611 unixUnmapfile(pFd);
4612 }
4613
4614 assert( pFd->nFetchOut>=0 );
4615 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004616}
4617
4618/*
drh734c9862008-11-28 15:37:20 +00004619** Here ends the implementation of all sqlite3_file methods.
4620**
4621********************** End sqlite3_file Methods *******************************
4622******************************************************************************/
4623
4624/*
drh6b9d6dd2008-12-03 19:34:47 +00004625** This division contains definitions of sqlite3_io_methods objects that
4626** implement various file locking strategies. It also contains definitions
4627** of "finder" functions. A finder-function is used to locate the appropriate
4628** sqlite3_io_methods object for a particular database file. The pAppData
4629** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4630** the correct finder-function for that VFS.
4631**
4632** Most finder functions return a pointer to a fixed sqlite3_io_methods
4633** object. The only interesting finder-function is autolockIoFinder, which
4634** looks at the filesystem type and tries to guess the best locking
4635** strategy from that.
4636**
drh1875f7a2008-12-08 18:19:17 +00004637** For finder-funtion F, two objects are created:
4638**
4639** (1) The real finder-function named "FImpt()".
4640**
dane946c392009-08-22 11:39:46 +00004641** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004642**
4643**
4644** A pointer to the F pointer is used as the pAppData value for VFS
4645** objects. We have to do this instead of letting pAppData point
4646** directly at the finder-function since C90 rules prevent a void*
4647** from be cast into a function pointer.
4648**
drh6b9d6dd2008-12-03 19:34:47 +00004649**
drh7708e972008-11-29 00:56:52 +00004650** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004651**
drh7708e972008-11-29 00:56:52 +00004652** * A constant sqlite3_io_methods object call METHOD that has locking
4653** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4654**
4655** * An I/O method finder function called FINDER that returns a pointer
4656** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004657*/
drhd9e5c4f2010-05-12 18:01:39 +00004658#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004659static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004660 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004661 CLOSE, /* xClose */ \
4662 unixRead, /* xRead */ \
4663 unixWrite, /* xWrite */ \
4664 unixTruncate, /* xTruncate */ \
4665 unixSync, /* xSync */ \
4666 unixFileSize, /* xFileSize */ \
4667 LOCK, /* xLock */ \
4668 UNLOCK, /* xUnlock */ \
4669 CKLOCK, /* xCheckReservedLock */ \
4670 unixFileControl, /* xFileControl */ \
4671 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004672 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004673 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004674 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004675 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004676 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004677 unixFetch, /* xFetch */ \
4678 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004679}; \
drh0c2694b2009-09-03 16:23:44 +00004680static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4681 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004682 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004683} \
drh0c2694b2009-09-03 16:23:44 +00004684static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004685 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004686
4687/*
4688** Here are all of the sqlite3_io_methods objects for each of the
4689** locking strategies. Functions that return pointers to these methods
4690** are also created.
4691*/
4692IOMETHODS(
4693 posixIoFinder, /* Finder function name */
4694 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004695 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004696 unixClose, /* xClose method */
4697 unixLock, /* xLock method */
4698 unixUnlock, /* xUnlock method */
4699 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004700)
drh7708e972008-11-29 00:56:52 +00004701IOMETHODS(
4702 nolockIoFinder, /* Finder function name */
4703 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004704 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004705 nolockClose, /* xClose method */
4706 nolockLock, /* xLock method */
4707 nolockUnlock, /* xUnlock method */
4708 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004709)
drh7708e972008-11-29 00:56:52 +00004710IOMETHODS(
4711 dotlockIoFinder, /* Finder function name */
4712 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004713 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004714 dotlockClose, /* xClose method */
4715 dotlockLock, /* xLock method */
4716 dotlockUnlock, /* xUnlock method */
4717 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004718)
drh7708e972008-11-29 00:56:52 +00004719
chw78a13182009-04-07 05:35:03 +00004720#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004721IOMETHODS(
4722 flockIoFinder, /* Finder function name */
4723 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004724 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004725 flockClose, /* xClose method */
4726 flockLock, /* xLock method */
4727 flockUnlock, /* xUnlock method */
4728 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004729)
drh7708e972008-11-29 00:56:52 +00004730#endif
4731
drh6c7d5c52008-11-21 20:32:33 +00004732#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004733IOMETHODS(
4734 semIoFinder, /* Finder function name */
4735 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004736 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004737 semClose, /* xClose method */
4738 semLock, /* xLock method */
4739 semUnlock, /* xUnlock method */
4740 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004741)
aswiftaebf4132008-11-21 00:10:35 +00004742#endif
drh7708e972008-11-29 00:56:52 +00004743
drhd2cb50b2009-01-09 21:41:17 +00004744#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004745IOMETHODS(
4746 afpIoFinder, /* Finder function name */
4747 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004748 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004749 afpClose, /* xClose method */
4750 afpLock, /* xLock method */
4751 afpUnlock, /* xUnlock method */
4752 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004753)
drh715ff302008-12-03 22:32:44 +00004754#endif
4755
4756/*
4757** The proxy locking method is a "super-method" in the sense that it
4758** opens secondary file descriptors for the conch and lock files and
4759** it uses proxy, dot-file, AFP, and flock() locking methods on those
4760** secondary files. For this reason, the division that implements
4761** proxy locking is located much further down in the file. But we need
4762** to go ahead and define the sqlite3_io_methods and finder function
4763** for proxy locking here. So we forward declare the I/O methods.
4764*/
drhd2cb50b2009-01-09 21:41:17 +00004765#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004766static int proxyClose(sqlite3_file*);
4767static int proxyLock(sqlite3_file*, int);
4768static int proxyUnlock(sqlite3_file*, int);
4769static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004770IOMETHODS(
4771 proxyIoFinder, /* Finder function name */
4772 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004773 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004774 proxyClose, /* xClose method */
4775 proxyLock, /* xLock method */
4776 proxyUnlock, /* xUnlock method */
4777 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004778)
aswiftaebf4132008-11-21 00:10:35 +00004779#endif
drh7708e972008-11-29 00:56:52 +00004780
drh7ed97b92010-01-20 13:07:21 +00004781/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4782#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4783IOMETHODS(
4784 nfsIoFinder, /* Finder function name */
4785 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004786 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004787 unixClose, /* xClose method */
4788 unixLock, /* xLock method */
4789 nfsUnlock, /* xUnlock method */
4790 unixCheckReservedLock /* xCheckReservedLock method */
4791)
4792#endif
drh7708e972008-11-29 00:56:52 +00004793
drhd2cb50b2009-01-09 21:41:17 +00004794#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004795/*
drh6b9d6dd2008-12-03 19:34:47 +00004796** This "finder" function attempts to determine the best locking strategy
4797** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004798** object that implements that strategy.
4799**
4800** This is for MacOSX only.
4801*/
drh1875f7a2008-12-08 18:19:17 +00004802static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004803 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004804 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004805){
4806 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004807 const char *zFilesystem; /* Filesystem type name */
4808 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004809 } aMap[] = {
4810 { "hfs", &posixIoMethods },
4811 { "ufs", &posixIoMethods },
4812 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004813 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004814 { "webdav", &nolockIoMethods },
4815 { 0, 0 }
4816 };
4817 int i;
4818 struct statfs fsInfo;
4819 struct flock lockInfo;
4820
4821 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004822 /* If filePath==NULL that means we are dealing with a transient file
4823 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004824 return &nolockIoMethods;
4825 }
4826 if( statfs(filePath, &fsInfo) != -1 ){
4827 if( fsInfo.f_flags & MNT_RDONLY ){
4828 return &nolockIoMethods;
4829 }
4830 for(i=0; aMap[i].zFilesystem; i++){
4831 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4832 return aMap[i].pMethods;
4833 }
4834 }
4835 }
4836
4837 /* Default case. Handles, amongst others, "nfs".
4838 ** Test byte-range lock using fcntl(). If the call succeeds,
4839 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004840 */
drh7708e972008-11-29 00:56:52 +00004841 lockInfo.l_len = 1;
4842 lockInfo.l_start = 0;
4843 lockInfo.l_whence = SEEK_SET;
4844 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004845 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004846 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4847 return &nfsIoMethods;
4848 } else {
4849 return &posixIoMethods;
4850 }
drh7708e972008-11-29 00:56:52 +00004851 }else{
4852 return &dotlockIoMethods;
4853 }
4854}
drh0c2694b2009-09-03 16:23:44 +00004855static const sqlite3_io_methods
4856 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004857
drhd2cb50b2009-01-09 21:41:17 +00004858#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004859
chw78a13182009-04-07 05:35:03 +00004860#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4861/*
4862** This "finder" function attempts to determine the best locking strategy
4863** for the database file "filePath". It then returns the sqlite3_io_methods
4864** object that implements that strategy.
4865**
4866** This is for VXWorks only.
4867*/
4868static const sqlite3_io_methods *autolockIoFinderImpl(
4869 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004870 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004871){
4872 struct flock lockInfo;
4873
4874 if( !filePath ){
4875 /* If filePath==NULL that means we are dealing with a transient file
4876 ** that does not need to be locked. */
4877 return &nolockIoMethods;
4878 }
4879
4880 /* Test if fcntl() is supported and use POSIX style locks.
4881 ** Otherwise fall back to the named semaphore method.
4882 */
4883 lockInfo.l_len = 1;
4884 lockInfo.l_start = 0;
4885 lockInfo.l_whence = SEEK_SET;
4886 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004887 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004888 return &posixIoMethods;
4889 }else{
4890 return &semIoMethods;
4891 }
4892}
drh0c2694b2009-09-03 16:23:44 +00004893static const sqlite3_io_methods
4894 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004895
4896#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4897
drh7708e972008-11-29 00:56:52 +00004898/*
4899** An abstract type for a pointer to a IO method finder function:
4900*/
drh0c2694b2009-09-03 16:23:44 +00004901typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004902
aswiftaebf4132008-11-21 00:10:35 +00004903
drh734c9862008-11-28 15:37:20 +00004904/****************************************************************************
4905**************************** sqlite3_vfs methods ****************************
4906**
4907** This division contains the implementation of methods on the
4908** sqlite3_vfs object.
4909*/
4910
danielk1977a3d4c882007-03-23 10:08:38 +00004911/*
danielk1977e339d652008-06-28 11:23:00 +00004912** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004913*/
4914static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004915 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004916 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004917 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004918 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004919 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004920){
drh7708e972008-11-29 00:56:52 +00004921 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004922 unixFile *pNew = (unixFile *)pId;
4923 int rc = SQLITE_OK;
4924
drh8af6c222010-05-14 12:43:01 +00004925 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004926
dan00157392010-10-05 11:33:15 +00004927 /* Usually the path zFilename should not be a relative pathname. The
4928 ** exception is when opening the proxy "conch" file in builds that
4929 ** include the special Apple locking styles.
4930 */
dan00157392010-10-05 11:33:15 +00004931#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004932 assert( zFilename==0 || zFilename[0]=='/'
4933 || pVfs->pAppData==(void*)&autolockIoFinder );
4934#else
4935 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004936#endif
dan00157392010-10-05 11:33:15 +00004937
drhb07028f2011-10-14 21:49:18 +00004938 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004939 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004940
drh308c2a52010-05-14 11:30:18 +00004941 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004942 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004943 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004944 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004945 pNew->ctrlFlags = (u8)ctrlFlags;
4946 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4947 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004948 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004949 }
drh503a6862013-03-01 01:07:17 +00004950 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00004951 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004952 }
drh339eb0b2008-03-07 15:34:11 +00004953
drh6c7d5c52008-11-21 20:32:33 +00004954#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004955 pNew->pId = vxworksFindFileId(zFilename);
4956 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004957 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004958 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004959 }
4960#endif
4961
drhc02a43a2012-01-10 23:18:38 +00004962 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004963 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004964 }else{
drh0c2694b2009-09-03 16:23:44 +00004965 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004966#if SQLITE_ENABLE_LOCKING_STYLE
4967 /* Cache zFilename in the locking context (AFP and dotlock override) for
4968 ** proxyLock activation is possible (remote proxy is based on db name)
4969 ** zFilename remains valid until file is closed, to support */
4970 pNew->lockingContext = (void*)zFilename;
4971#endif
drhda0e7682008-07-30 15:27:54 +00004972 }
danielk1977e339d652008-06-28 11:23:00 +00004973
drh7ed97b92010-01-20 13:07:21 +00004974 if( pLockingStyle == &posixIoMethods
4975#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4976 || pLockingStyle == &nfsIoMethods
4977#endif
4978 ){
drh7708e972008-11-29 00:56:52 +00004979 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004980 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004981 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004982 /* If an error occured in findInodeInfo(), close the file descriptor
4983 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004984 ** in two scenarios:
4985 **
4986 ** (a) A call to fstat() failed.
4987 ** (b) A malloc failed.
4988 **
4989 ** Scenario (b) may only occur if the process is holding no other
4990 ** file descriptors open on the same file. If there were other file
4991 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004992 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004993 ** handle h - as it is guaranteed that no posix locks will be released
4994 ** by doing so.
4995 **
4996 ** If scenario (a) caused the error then things are not so safe. The
4997 ** implicit assumption here is that if fstat() fails, things are in
4998 ** such bad shape that dropping a lock or two doesn't matter much.
4999 */
drh0e9365c2011-03-02 02:08:13 +00005000 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005001 h = -1;
5002 }
drh7708e972008-11-29 00:56:52 +00005003 unixLeaveMutex();
5004 }
danielk1977e339d652008-06-28 11:23:00 +00005005
drhd2cb50b2009-01-09 21:41:17 +00005006#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005007 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005008 /* AFP locking uses the file path so it needs to be included in
5009 ** the afpLockingContext.
5010 */
5011 afpLockingContext *pCtx;
5012 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5013 if( pCtx==0 ){
5014 rc = SQLITE_NOMEM;
5015 }else{
5016 /* NB: zFilename exists and remains valid until the file is closed
5017 ** according to requirement F11141. So we do not need to make a
5018 ** copy of the filename. */
5019 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005020 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005021 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005022 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005023 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005024 if( rc!=SQLITE_OK ){
5025 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005026 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005027 h = -1;
5028 }
drh7708e972008-11-29 00:56:52 +00005029 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005030 }
drh7708e972008-11-29 00:56:52 +00005031 }
5032#endif
danielk1977e339d652008-06-28 11:23:00 +00005033
drh7708e972008-11-29 00:56:52 +00005034 else if( pLockingStyle == &dotlockIoMethods ){
5035 /* Dotfile locking uses the file path so it needs to be included in
5036 ** the dotlockLockingContext
5037 */
5038 char *zLockFile;
5039 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005040 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005041 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005042 zLockFile = (char *)sqlite3_malloc(nFilename);
5043 if( zLockFile==0 ){
5044 rc = SQLITE_NOMEM;
5045 }else{
5046 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005047 }
drh7708e972008-11-29 00:56:52 +00005048 pNew->lockingContext = zLockFile;
5049 }
danielk1977e339d652008-06-28 11:23:00 +00005050
drh6c7d5c52008-11-21 20:32:33 +00005051#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005052 else if( pLockingStyle == &semIoMethods ){
5053 /* Named semaphore locking uses the file path so it needs to be
5054 ** included in the semLockingContext
5055 */
5056 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005057 rc = findInodeInfo(pNew, &pNew->pInode);
5058 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5059 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005060 int n;
drh2238dcc2009-08-27 17:56:20 +00005061 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005062 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005063 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005064 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005065 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5066 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005067 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005068 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005069 }
chw97185482008-11-17 08:05:31 +00005070 }
drh7708e972008-11-29 00:56:52 +00005071 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005072 }
drh7708e972008-11-29 00:56:52 +00005073#endif
aswift5b1a2562008-08-22 00:22:35 +00005074
5075 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005076#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005077 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005078 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005079 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005080 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00005081 isDelete = 0;
5082 }
drhc02a43a2012-01-10 23:18:38 +00005083 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005084#endif
danielk1977e339d652008-06-28 11:23:00 +00005085 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005086 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005087 }else{
drh7708e972008-11-29 00:56:52 +00005088 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005089 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00005090 }
danielk1977e339d652008-06-28 11:23:00 +00005091 return rc;
drh054889e2005-11-30 03:20:31 +00005092}
drh9c06c952005-11-26 00:25:00 +00005093
danielk1977ad94b582007-08-20 06:44:22 +00005094/*
drh8b3cf822010-06-01 21:02:51 +00005095** Return the name of a directory in which to put temporary files.
5096** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005097*/
drh7234c6d2010-06-19 15:10:09 +00005098static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005099 static const char *azDirs[] = {
5100 0,
aswiftaebf4132008-11-21 00:10:35 +00005101 0,
danielk197717b90b52008-06-06 11:11:25 +00005102 "/var/tmp",
5103 "/usr/tmp",
5104 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005105 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005106 };
drh8b3cf822010-06-01 21:02:51 +00005107 unsigned int i;
5108 struct stat buf;
5109 const char *zDir = 0;
5110
5111 azDirs[0] = sqlite3_temp_directory;
5112 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005113 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005114 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005115 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005116 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005117 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005118 break;
5119 }
5120 return zDir;
5121}
5122
5123/*
5124** Create a temporary file name in zBuf. zBuf must be allocated
5125** by the calling process and must be big enough to hold at least
5126** pVfs->mxPathname bytes.
5127*/
5128static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005129 static const unsigned char zChars[] =
5130 "abcdefghijklmnopqrstuvwxyz"
5131 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5132 "0123456789";
drh41022642008-11-21 00:24:42 +00005133 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005134 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005135
5136 /* It's odd to simulate an io-error here, but really this is just
5137 ** using the io-error infrastructure to test that SQLite handles this
5138 ** function failing.
5139 */
5140 SimulateIOError( return SQLITE_IOERR );
5141
drh7234c6d2010-06-19 15:10:09 +00005142 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005143 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005144
5145 /* Check that the output buffer is large enough for the temporary file
5146 ** name. If it is not, return SQLITE_ERROR.
5147 */
drhc02a43a2012-01-10 23:18:38 +00005148 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005149 return SQLITE_ERROR;
5150 }
5151
5152 do{
drhc02a43a2012-01-10 23:18:38 +00005153 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005154 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005155 sqlite3_randomness(15, &zBuf[j]);
5156 for(i=0; i<15; i++, j++){
5157 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5158 }
5159 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005160 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005161 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005162 return SQLITE_OK;
5163}
5164
drhd2cb50b2009-01-09 21:41:17 +00005165#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005166/*
5167** Routine to transform a unixFile into a proxy-locking unixFile.
5168** Implementation in the proxy-lock division, but used by unixOpen()
5169** if SQLITE_PREFER_PROXY_LOCKING is defined.
5170*/
5171static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005172#endif
drhc66d5b62008-12-03 22:48:32 +00005173
dan08da86a2009-08-21 17:18:03 +00005174/*
5175** Search for an unused file descriptor that was opened on the database
5176** file (not a journal or master-journal file) identified by pathname
5177** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5178** argument to this function.
5179**
5180** Such a file descriptor may exist if a database connection was closed
5181** but the associated file descriptor could not be closed because some
5182** other file descriptor open on the same file is holding a file-lock.
5183** Refer to comments in the unixClose() function and the lengthy comment
5184** describing "Posix Advisory Locking" at the start of this file for
5185** further details. Also, ticket #4018.
5186**
5187** If a suitable file descriptor is found, then it is returned. If no
5188** such file descriptor is located, -1 is returned.
5189*/
dane946c392009-08-22 11:39:46 +00005190static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5191 UnixUnusedFd *pUnused = 0;
5192
5193 /* Do not search for an unused file descriptor on vxworks. Not because
5194 ** vxworks would not benefit from the change (it might, we're not sure),
5195 ** but because no way to test it is currently available. It is better
5196 ** not to risk breaking vxworks support for the sake of such an obscure
5197 ** feature. */
5198#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005199 struct stat sStat; /* Results of stat() call */
5200
5201 /* A stat() call may fail for various reasons. If this happens, it is
5202 ** almost certain that an open() call on the same path will also fail.
5203 ** For this reason, if an error occurs in the stat() call here, it is
5204 ** ignored and -1 is returned. The caller will try to open a new file
5205 ** descriptor on the same path, fail, and return an error to SQLite.
5206 **
5207 ** Even if a subsequent open() call does succeed, the consequences of
5208 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005209 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005210 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005211
5212 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005213 pInode = inodeList;
5214 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5215 || pInode->fileId.ino!=sStat.st_ino) ){
5216 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005217 }
drh8af6c222010-05-14 12:43:01 +00005218 if( pInode ){
dane946c392009-08-22 11:39:46 +00005219 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005220 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005221 pUnused = *pp;
5222 if( pUnused ){
5223 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005224 }
5225 }
5226 unixLeaveMutex();
5227 }
dane946c392009-08-22 11:39:46 +00005228#endif /* if !OS_VXWORKS */
5229 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005230}
danielk197717b90b52008-06-06 11:11:25 +00005231
5232/*
danddb0ac42010-07-14 14:48:58 +00005233** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005234** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005235** and a value suitable for passing as the third argument to open(2) is
5236** written to *pMode. If an IO error occurs, an SQLite error code is
5237** returned and the value of *pMode is not modified.
5238**
drh8c815d12012-02-13 20:16:37 +00005239** In most cases cases, this routine sets *pMode to 0, which will become
5240** an indication to robust_open() to create the file using
5241** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5242** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005243** this function queries the file-system for the permissions on the
5244** corresponding database file and sets *pMode to this value. Whenever
5245** possible, WAL and journal files are created using the same permissions
5246** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005247**
5248** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5249** original filename is unavailable. But 8_3_NAMES is only used for
5250** FAT filesystems and permissions do not matter there, so just use
5251** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005252*/
5253static int findCreateFileMode(
5254 const char *zPath, /* Path of file (possibly) being created */
5255 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005256 mode_t *pMode, /* OUT: Permissions to open file with */
5257 uid_t *pUid, /* OUT: uid to set on the file */
5258 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005259){
5260 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005261 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005262 *pUid = 0;
5263 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005264 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005265 char zDb[MAX_PATHNAME+1]; /* Database file path */
5266 int nDb; /* Number of valid bytes in zDb */
5267 struct stat sStat; /* Output of stat() on database file */
5268
dana0c989d2010-11-05 18:07:37 +00005269 /* zPath is a path to a WAL or journal file. The following block derives
5270 ** the path to the associated database file from zPath. This block handles
5271 ** the following naming conventions:
5272 **
5273 ** "<path to db>-journal"
5274 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005275 ** "<path to db>-journalNN"
5276 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005277 **
drhd337c5b2011-10-20 18:23:35 +00005278 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005279 ** used by the test_multiplex.c module.
5280 */
5281 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005282#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005283 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005284 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005285#else
5286 while( zPath[nDb]!='-' ){
5287 assert( nDb>0 );
5288 assert( zPath[nDb]!='\n' );
5289 nDb--;
5290 }
5291#endif
danddb0ac42010-07-14 14:48:58 +00005292 memcpy(zDb, zPath, nDb);
5293 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005294
drh58384f12011-07-28 00:14:45 +00005295 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005296 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005297 *pUid = sStat.st_uid;
5298 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005299 }else{
5300 rc = SQLITE_IOERR_FSTAT;
5301 }
5302 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5303 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005304 }
5305 return rc;
5306}
5307
5308/*
danielk1977ad94b582007-08-20 06:44:22 +00005309** Open the file zPath.
5310**
danielk1977b4b47412007-08-17 15:53:36 +00005311** Previously, the SQLite OS layer used three functions in place of this
5312** one:
5313**
5314** sqlite3OsOpenReadWrite();
5315** sqlite3OsOpenReadOnly();
5316** sqlite3OsOpenExclusive();
5317**
5318** These calls correspond to the following combinations of flags:
5319**
5320** ReadWrite() -> (READWRITE | CREATE)
5321** ReadOnly() -> (READONLY)
5322** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5323**
5324** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5325** true, the file was configured to be automatically deleted when the
5326** file handle closed. To achieve the same effect using this new
5327** interface, add the DELETEONCLOSE flag to those specified above for
5328** OpenExclusive().
5329*/
5330static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005331 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5332 const char *zPath, /* Pathname of file to be opened */
5333 sqlite3_file *pFile, /* The file descriptor to be filled in */
5334 int flags, /* Input flags to control the opening */
5335 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005336){
dan08da86a2009-08-21 17:18:03 +00005337 unixFile *p = (unixFile *)pFile;
5338 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005339 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005340 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005341 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005342 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005343 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005344
5345 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5346 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5347 int isCreate = (flags & SQLITE_OPEN_CREATE);
5348 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5349 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005350#if SQLITE_ENABLE_LOCKING_STYLE
5351 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5352#endif
drh3d4435b2011-08-26 20:55:50 +00005353#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5354 struct statfs fsInfo;
5355#endif
danielk1977b4b47412007-08-17 15:53:36 +00005356
danielk1977fee2d252007-08-18 10:59:19 +00005357 /* If creating a master or main-file journal, this function will open
5358 ** a file-descriptor on the directory too. The first time unixSync()
5359 ** is called the directory file descriptor will be fsync()ed and close()d.
5360 */
drh0059eae2011-08-08 23:48:40 +00005361 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005362 eType==SQLITE_OPEN_MASTER_JOURNAL
5363 || eType==SQLITE_OPEN_MAIN_JOURNAL
5364 || eType==SQLITE_OPEN_WAL
5365 ));
danielk1977fee2d252007-08-18 10:59:19 +00005366
danielk197717b90b52008-06-06 11:11:25 +00005367 /* If argument zPath is a NULL pointer, this function is required to open
5368 ** a temporary file. Use this buffer to store the file name in.
5369 */
drhc02a43a2012-01-10 23:18:38 +00005370 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005371 const char *zName = zPath;
5372
danielk1977fee2d252007-08-18 10:59:19 +00005373 /* Check the following statements are true:
5374 **
5375 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5376 ** (b) if CREATE is set, then READWRITE must also be set, and
5377 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005378 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005379 */
danielk1977b4b47412007-08-17 15:53:36 +00005380 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005381 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005382 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005383 assert(isDelete==0 || isCreate);
5384
danddb0ac42010-07-14 14:48:58 +00005385 /* The main DB, main journal, WAL file and master journal are never
5386 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005387 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5388 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5389 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005390 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005391
danielk1977fee2d252007-08-18 10:59:19 +00005392 /* Assert that the upper layer has set one of the "file-type" flags. */
5393 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5394 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5395 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005396 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005397 );
5398
dan08da86a2009-08-21 17:18:03 +00005399 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005400
dan08da86a2009-08-21 17:18:03 +00005401 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005402 UnixUnusedFd *pUnused;
5403 pUnused = findReusableFd(zName, flags);
5404 if( pUnused ){
5405 fd = pUnused->fd;
5406 }else{
dan6aa657f2009-08-24 18:57:58 +00005407 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005408 if( !pUnused ){
5409 return SQLITE_NOMEM;
5410 }
5411 }
5412 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005413
5414 /* Database filenames are double-zero terminated if they are not
5415 ** URIs with parameters. Hence, they can always be passed into
5416 ** sqlite3_uri_parameter(). */
5417 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5418
dan08da86a2009-08-21 17:18:03 +00005419 }else if( !zName ){
5420 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005421 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005422 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005423 if( rc!=SQLITE_OK ){
5424 return rc;
5425 }
5426 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005427
5428 /* Generated temporary filenames are always double-zero terminated
5429 ** for use by sqlite3_uri_parameter(). */
5430 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005431 }
5432
dan08da86a2009-08-21 17:18:03 +00005433 /* Determine the value of the flags parameter passed to POSIX function
5434 ** open(). These must be calculated even if open() is not called, as
5435 ** they may be stored as part of the file handle and used by the
5436 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005437 if( isReadonly ) openFlags |= O_RDONLY;
5438 if( isReadWrite ) openFlags |= O_RDWR;
5439 if( isCreate ) openFlags |= O_CREAT;
5440 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5441 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005442
danielk1977b4b47412007-08-17 15:53:36 +00005443 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005444 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005445 uid_t uid; /* Userid for the file */
5446 gid_t gid; /* Groupid for the file */
5447 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005448 if( rc!=SQLITE_OK ){
5449 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005450 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005451 return rc;
5452 }
drhad4f1e52011-03-04 15:43:57 +00005453 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005454 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005455 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5456 /* Failed to open the file for read/write access. Try read-only. */
5457 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005458 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005459 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005460 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005461 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005462 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005463 }
5464 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005465 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005466 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005467 }
drhac7c3ac2012-02-11 19:23:48 +00005468
5469 /* If this process is running as root and if creating a new rollback
5470 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005471 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005472 */
5473 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005474 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005475 }
danielk1977b4b47412007-08-17 15:53:36 +00005476 }
dan08da86a2009-08-21 17:18:03 +00005477 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005478 if( pOutFlags ){
5479 *pOutFlags = flags;
5480 }
5481
dane946c392009-08-22 11:39:46 +00005482 if( p->pUnused ){
5483 p->pUnused->fd = fd;
5484 p->pUnused->flags = flags;
5485 }
5486
danielk1977b4b47412007-08-17 15:53:36 +00005487 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005488#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005489 zPath = zName;
5490#else
drh036ac7f2011-08-08 23:18:05 +00005491 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005492#endif
danielk1977b4b47412007-08-17 15:53:36 +00005493 }
drh41022642008-11-21 00:24:42 +00005494#if SQLITE_ENABLE_LOCKING_STYLE
5495 else{
dan08da86a2009-08-21 17:18:03 +00005496 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005497 }
5498#endif
5499
drhda0e7682008-07-30 15:27:54 +00005500 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005501
drh7ed97b92010-01-20 13:07:21 +00005502
5503#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005504 if( fstatfs(fd, &fsInfo) == -1 ){
5505 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005506 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005507 return SQLITE_IOERR_ACCESS;
5508 }
5509 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5510 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5511 }
5512#endif
drhc02a43a2012-01-10 23:18:38 +00005513
5514 /* Set up appropriate ctrlFlags */
5515 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5516 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5517 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5518 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5519 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5520
drh7ed97b92010-01-20 13:07:21 +00005521#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005522#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005523 isAutoProxy = 1;
5524#endif
5525 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005526 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5527 int useProxy = 0;
5528
dan08da86a2009-08-21 17:18:03 +00005529 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5530 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005531 if( envforce!=NULL ){
5532 useProxy = atoi(envforce)>0;
5533 }else{
aswiftaebf4132008-11-21 00:10:35 +00005534 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005535 /* In theory, the close(fd) call is sub-optimal. If the file opened
5536 ** with fd is a database file, and there are other connections open
5537 ** on that file that are currently holding advisory locks on it,
5538 ** then the call to close() will cancel those locks. In practice,
5539 ** we're assuming that statfs() doesn't fail very often. At least
5540 ** not while other file descriptors opened by the same process on
5541 ** the same file are working. */
5542 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005543 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005544 rc = SQLITE_IOERR_ACCESS;
5545 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005546 }
5547 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5548 }
5549 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005550 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005551 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005552 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005553 if( rc!=SQLITE_OK ){
5554 /* Use unixClose to clean up the resources added in fillInUnixFile
5555 ** and clear all the structure's references. Specifically,
5556 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5557 */
5558 unixClose(pFile);
5559 return rc;
5560 }
aswiftaebf4132008-11-21 00:10:35 +00005561 }
dane946c392009-08-22 11:39:46 +00005562 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005563 }
5564 }
5565#endif
5566
drhc02a43a2012-01-10 23:18:38 +00005567 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5568
dane946c392009-08-22 11:39:46 +00005569open_finished:
5570 if( rc!=SQLITE_OK ){
5571 sqlite3_free(p->pUnused);
5572 }
5573 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005574}
5575
dane946c392009-08-22 11:39:46 +00005576
danielk1977b4b47412007-08-17 15:53:36 +00005577/*
danielk1977fee2d252007-08-18 10:59:19 +00005578** Delete the file at zPath. If the dirSync argument is true, fsync()
5579** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005580*/
drh6b9d6dd2008-12-03 19:34:47 +00005581static int unixDelete(
5582 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5583 const char *zPath, /* Name of file to be deleted */
5584 int dirSync /* If true, fsync() directory after deleting file */
5585){
danielk1977fee2d252007-08-18 10:59:19 +00005586 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005587 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005588 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005589 if( osUnlink(zPath)==(-1) ){
5590 if( errno==ENOENT ){
5591 rc = SQLITE_IOERR_DELETE_NOENT;
5592 }else{
drhb4308162012-11-09 21:40:02 +00005593 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005594 }
drhb4308162012-11-09 21:40:02 +00005595 return rc;
drh5d4feff2010-07-14 01:45:22 +00005596 }
danielk1977d39fa702008-10-16 13:27:40 +00005597#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005598 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005599 int fd;
drh90315a22011-08-10 01:52:12 +00005600 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005601 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005602#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005603 if( fsync(fd)==-1 )
5604#else
5605 if( fsync(fd) )
5606#endif
5607 {
dane18d4952011-02-21 11:46:24 +00005608 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005609 }
drh0e9365c2011-03-02 02:08:13 +00005610 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005611 }else if( rc==SQLITE_CANTOPEN ){
5612 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005613 }
5614 }
danielk1977d138dd82008-10-15 16:02:48 +00005615#endif
danielk1977fee2d252007-08-18 10:59:19 +00005616 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005617}
5618
danielk197790949c22007-08-17 16:50:38 +00005619/*
5620** Test the existance of or access permissions of file zPath. The
5621** test performed depends on the value of flags:
5622**
5623** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5624** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5625** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5626**
5627** Otherwise return 0.
5628*/
danielk1977861f7452008-06-05 11:39:11 +00005629static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005630 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5631 const char *zPath, /* Path of the file to examine */
5632 int flags, /* What do we want to learn about the zPath file? */
5633 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005634){
rse25c0d1a2007-09-20 08:38:14 +00005635 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005636 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005637 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005638 switch( flags ){
5639 case SQLITE_ACCESS_EXISTS:
5640 amode = F_OK;
5641 break;
5642 case SQLITE_ACCESS_READWRITE:
5643 amode = W_OK|R_OK;
5644 break;
drh50d3f902007-08-27 21:10:36 +00005645 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005646 amode = R_OK;
5647 break;
5648
5649 default:
5650 assert(!"Invalid flags argument");
5651 }
drh99ab3b12011-03-02 15:09:07 +00005652 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005653 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5654 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005655 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005656 *pResOut = 0;
5657 }
5658 }
danielk1977861f7452008-06-05 11:39:11 +00005659 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005660}
5661
danielk1977b4b47412007-08-17 15:53:36 +00005662
5663/*
5664** Turn a relative pathname into a full pathname. The relative path
5665** is stored as a nul-terminated string in the buffer pointed to by
5666** zPath.
5667**
5668** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5669** (in this case, MAX_PATHNAME bytes). The full-path is written to
5670** this buffer before returning.
5671*/
danielk1977adfb9b02007-09-17 07:02:56 +00005672static int unixFullPathname(
5673 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5674 const char *zPath, /* Possibly relative input path */
5675 int nOut, /* Size of output buffer in bytes */
5676 char *zOut /* Output buffer */
5677){
danielk1977843e65f2007-09-01 16:16:15 +00005678
5679 /* It's odd to simulate an io-error here, but really this is just
5680 ** using the io-error infrastructure to test that SQLite handles this
5681 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005682 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005683 */
5684 SimulateIOError( return SQLITE_ERROR );
5685
drh153c62c2007-08-24 03:51:33 +00005686 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005687 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005688
drh3c7f2dc2007-12-06 13:26:20 +00005689 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005690 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005691 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005692 }else{
5693 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005694 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005695 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005696 }
drhea678832008-12-10 19:26:22 +00005697 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005698 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005699 }
5700 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005701}
5702
drh0ccebe72005-06-07 22:22:50 +00005703
drh761df872006-12-21 01:29:22 +00005704#ifndef SQLITE_OMIT_LOAD_EXTENSION
5705/*
5706** Interfaces for opening a shared library, finding entry points
5707** within the shared library, and closing the shared library.
5708*/
5709#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005710static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5711 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005712 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5713}
danielk197795c8a542007-09-01 06:51:27 +00005714
5715/*
5716** SQLite calls this function immediately after a call to unixDlSym() or
5717** unixDlOpen() fails (returns a null pointer). If a more detailed error
5718** message is available, it is written to zBufOut. If no error message
5719** is available, zBufOut is left unmodified and SQLite uses a default
5720** error message.
5721*/
danielk1977397d65f2008-11-19 11:35:39 +00005722static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005723 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005724 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005725 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005726 zErr = dlerror();
5727 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005728 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005729 }
drh6c7d5c52008-11-21 20:32:33 +00005730 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005731}
drh1875f7a2008-12-08 18:19:17 +00005732static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5733 /*
5734 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5735 ** cast into a pointer to a function. And yet the library dlsym() routine
5736 ** returns a void* which is really a pointer to a function. So how do we
5737 ** use dlsym() with -pedantic-errors?
5738 **
5739 ** Variable x below is defined to be a pointer to a function taking
5740 ** parameters void* and const char* and returning a pointer to a function.
5741 ** We initialize x by assigning it a pointer to the dlsym() function.
5742 ** (That assignment requires a cast.) Then we call the function that
5743 ** x points to.
5744 **
5745 ** This work-around is unlikely to work correctly on any system where
5746 ** you really cannot cast a function pointer into void*. But then, on the
5747 ** other hand, dlsym() will not work on such a system either, so we have
5748 ** not really lost anything.
5749 */
5750 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005751 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005752 x = (void(*(*)(void*,const char*))(void))dlsym;
5753 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005754}
danielk1977397d65f2008-11-19 11:35:39 +00005755static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5756 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005757 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005758}
danielk1977b4b47412007-08-17 15:53:36 +00005759#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5760 #define unixDlOpen 0
5761 #define unixDlError 0
5762 #define unixDlSym 0
5763 #define unixDlClose 0
5764#endif
5765
5766/*
danielk197790949c22007-08-17 16:50:38 +00005767** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005768*/
danielk1977397d65f2008-11-19 11:35:39 +00005769static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5770 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005771 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005772
drhbbd42a62004-05-22 17:41:58 +00005773 /* We have to initialize zBuf to prevent valgrind from reporting
5774 ** errors. The reports issued by valgrind are incorrect - we would
5775 ** prefer that the randomness be increased by making use of the
5776 ** uninitialized space in zBuf - but valgrind errors tend to worry
5777 ** some users. Rather than argue, it seems easier just to initialize
5778 ** the whole array and silence valgrind, even if that means less randomness
5779 ** in the random seed.
5780 **
5781 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005782 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005783 ** tests repeatable.
5784 */
danielk1977b4b47412007-08-17 15:53:36 +00005785 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005786#if !defined(SQLITE_TEST)
5787 {
drhc18b4042012-02-10 03:10:27 +00005788 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005789 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005790 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005791 time_t t;
5792 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005793 memcpy(zBuf, &t, sizeof(t));
5794 pid = getpid();
5795 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005796 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005797 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005798 }else{
drhc18b4042012-02-10 03:10:27 +00005799 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005800 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005801 }
drhbbd42a62004-05-22 17:41:58 +00005802 }
5803#endif
drh72cbd072008-10-14 17:58:38 +00005804 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005805}
5806
danielk1977b4b47412007-08-17 15:53:36 +00005807
drhbbd42a62004-05-22 17:41:58 +00005808/*
5809** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005810** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005811** The return value is the number of microseconds of sleep actually
5812** requested from the underlying operating system, a number which
5813** might be greater than or equal to the argument, but not less
5814** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005815*/
danielk1977397d65f2008-11-19 11:35:39 +00005816static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005817#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005818 struct timespec sp;
5819
5820 sp.tv_sec = microseconds / 1000000;
5821 sp.tv_nsec = (microseconds % 1000000) * 1000;
5822 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005823 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005824 return microseconds;
5825#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005826 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005827 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005828 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005829#else
danielk1977b4b47412007-08-17 15:53:36 +00005830 int seconds = (microseconds+999999)/1000000;
5831 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005832 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005833 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005834#endif
drh88f474a2006-01-02 20:00:12 +00005835}
5836
5837/*
drh6b9d6dd2008-12-03 19:34:47 +00005838** The following variable, if set to a non-zero value, is interpreted as
5839** the number of seconds since 1970 and is used to set the result of
5840** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005841*/
5842#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005843int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005844#endif
5845
5846/*
drhb7e8ea22010-05-03 14:32:30 +00005847** Find the current time (in Universal Coordinated Time). Write into *piNow
5848** the current time and date as a Julian Day number times 86_400_000. In
5849** other words, write into *piNow the number of milliseconds since the Julian
5850** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5851** proleptic Gregorian calendar.
5852**
drh31702252011-10-12 23:13:43 +00005853** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5854** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005855*/
5856static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5857 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005858 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005859#if defined(NO_GETTOD)
5860 time_t t;
5861 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005862 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005863#elif OS_VXWORKS
5864 struct timespec sNow;
5865 clock_gettime(CLOCK_REALTIME, &sNow);
5866 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5867#else
5868 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005869 if( gettimeofday(&sNow, 0)==0 ){
5870 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5871 }else{
5872 rc = SQLITE_ERROR;
5873 }
drhb7e8ea22010-05-03 14:32:30 +00005874#endif
5875
5876#ifdef SQLITE_TEST
5877 if( sqlite3_current_time ){
5878 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5879 }
5880#endif
5881 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005882 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005883}
5884
5885/*
drhbbd42a62004-05-22 17:41:58 +00005886** Find the current time (in Universal Coordinated Time). Write the
5887** current time and date as a Julian Day number into *prNow and
5888** return 0. Return 1 if the time and date cannot be found.
5889*/
danielk1977397d65f2008-11-19 11:35:39 +00005890static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005891 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005892 int rc;
drhff828942010-06-26 21:34:06 +00005893 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005894 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005895 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005896 return rc;
drhbbd42a62004-05-22 17:41:58 +00005897}
danielk1977b4b47412007-08-17 15:53:36 +00005898
drh6b9d6dd2008-12-03 19:34:47 +00005899/*
5900** We added the xGetLastError() method with the intention of providing
5901** better low-level error messages when operating-system problems come up
5902** during SQLite operation. But so far, none of that has been implemented
5903** in the core. So this routine is never called. For now, it is merely
5904** a place-holder.
5905*/
danielk1977397d65f2008-11-19 11:35:39 +00005906static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5907 UNUSED_PARAMETER(NotUsed);
5908 UNUSED_PARAMETER(NotUsed2);
5909 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005910 return 0;
5911}
5912
drhf2424c52010-04-26 00:04:55 +00005913
5914/*
drh734c9862008-11-28 15:37:20 +00005915************************ End of sqlite3_vfs methods ***************************
5916******************************************************************************/
5917
drh715ff302008-12-03 22:32:44 +00005918/******************************************************************************
5919************************** Begin Proxy Locking ********************************
5920**
5921** Proxy locking is a "uber-locking-method" in this sense: It uses the
5922** other locking methods on secondary lock files. Proxy locking is a
5923** meta-layer over top of the primitive locking implemented above. For
5924** this reason, the division that implements of proxy locking is deferred
5925** until late in the file (here) after all of the other I/O methods have
5926** been defined - so that the primitive locking methods are available
5927** as services to help with the implementation of proxy locking.
5928**
5929****
5930**
5931** The default locking schemes in SQLite use byte-range locks on the
5932** database file to coordinate safe, concurrent access by multiple readers
5933** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5934** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5935** as POSIX read & write locks over fixed set of locations (via fsctl),
5936** on AFP and SMB only exclusive byte-range locks are available via fsctl
5937** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5938** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5939** address in the shared range is taken for a SHARED lock, the entire
5940** shared range is taken for an EXCLUSIVE lock):
5941**
drhf2f105d2012-08-20 15:53:54 +00005942** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00005943** RESERVED_BYTE 0x40000001
5944** SHARED_RANGE 0x40000002 -> 0x40000200
5945**
5946** This works well on the local file system, but shows a nearly 100x
5947** slowdown in read performance on AFP because the AFP client disables
5948** the read cache when byte-range locks are present. Enabling the read
5949** cache exposes a cache coherency problem that is present on all OS X
5950** supported network file systems. NFS and AFP both observe the
5951** close-to-open semantics for ensuring cache coherency
5952** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5953** address the requirements for concurrent database access by multiple
5954** readers and writers
5955** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5956**
5957** To address the performance and cache coherency issues, proxy file locking
5958** changes the way database access is controlled by limiting access to a
5959** single host at a time and moving file locks off of the database file
5960** and onto a proxy file on the local file system.
5961**
5962**
5963** Using proxy locks
5964** -----------------
5965**
5966** C APIs
5967**
5968** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5969** <proxy_path> | ":auto:");
5970** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5971**
5972**
5973** SQL pragmas
5974**
5975** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5976** PRAGMA [database.]lock_proxy_file
5977**
5978** Specifying ":auto:" means that if there is a conch file with a matching
5979** host ID in it, the proxy path in the conch file will be used, otherwise
5980** a proxy path based on the user's temp dir
5981** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5982** actual proxy file name is generated from the name and path of the
5983** database file. For example:
5984**
5985** For database path "/Users/me/foo.db"
5986** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5987**
5988** Once a lock proxy is configured for a database connection, it can not
5989** be removed, however it may be switched to a different proxy path via
5990** the above APIs (assuming the conch file is not being held by another
5991** connection or process).
5992**
5993**
5994** How proxy locking works
5995** -----------------------
5996**
5997** Proxy file locking relies primarily on two new supporting files:
5998**
5999** * conch file to limit access to the database file to a single host
6000** at a time
6001**
6002** * proxy file to act as a proxy for the advisory locks normally
6003** taken on the database
6004**
6005** The conch file - to use a proxy file, sqlite must first "hold the conch"
6006** by taking an sqlite-style shared lock on the conch file, reading the
6007** contents and comparing the host's unique host ID (see below) and lock
6008** proxy path against the values stored in the conch. The conch file is
6009** stored in the same directory as the database file and the file name
6010** is patterned after the database file name as ".<databasename>-conch".
6011** If the conch file does not exist, or it's contents do not match the
6012** host ID and/or proxy path, then the lock is escalated to an exclusive
6013** lock and the conch file contents is updated with the host ID and proxy
6014** path and the lock is downgraded to a shared lock again. If the conch
6015** is held by another process (with a shared lock), the exclusive lock
6016** will fail and SQLITE_BUSY is returned.
6017**
6018** The proxy file - a single-byte file used for all advisory file locks
6019** normally taken on the database file. This allows for safe sharing
6020** of the database file for multiple readers and writers on the same
6021** host (the conch ensures that they all use the same local lock file).
6022**
drh715ff302008-12-03 22:32:44 +00006023** Requesting the lock proxy does not immediately take the conch, it is
6024** only taken when the first request to lock database file is made.
6025** This matches the semantics of the traditional locking behavior, where
6026** opening a connection to a database file does not take a lock on it.
6027** The shared lock and an open file descriptor are maintained until
6028** the connection to the database is closed.
6029**
6030** The proxy file and the lock file are never deleted so they only need
6031** to be created the first time they are used.
6032**
6033** Configuration options
6034** ---------------------
6035**
6036** SQLITE_PREFER_PROXY_LOCKING
6037**
6038** Database files accessed on non-local file systems are
6039** automatically configured for proxy locking, lock files are
6040** named automatically using the same logic as
6041** PRAGMA lock_proxy_file=":auto:"
6042**
6043** SQLITE_PROXY_DEBUG
6044**
6045** Enables the logging of error messages during host id file
6046** retrieval and creation
6047**
drh715ff302008-12-03 22:32:44 +00006048** LOCKPROXYDIR
6049**
6050** Overrides the default directory used for lock proxy files that
6051** are named automatically via the ":auto:" setting
6052**
6053** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6054**
6055** Permissions to use when creating a directory for storing the
6056** lock proxy files, only used when LOCKPROXYDIR is not set.
6057**
6058**
6059** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6060** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6061** force proxy locking to be used for every database file opened, and 0
6062** will force automatic proxy locking to be disabled for all database
6063** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6064** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6065*/
6066
6067/*
6068** Proxy locking is only available on MacOSX
6069*/
drhd2cb50b2009-01-09 21:41:17 +00006070#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006071
drh715ff302008-12-03 22:32:44 +00006072/*
6073** The proxyLockingContext has the path and file structures for the remote
6074** and local proxy files in it
6075*/
6076typedef struct proxyLockingContext proxyLockingContext;
6077struct proxyLockingContext {
6078 unixFile *conchFile; /* Open conch file */
6079 char *conchFilePath; /* Name of the conch file */
6080 unixFile *lockProxy; /* Open proxy lock file */
6081 char *lockProxyPath; /* Name of the proxy lock file */
6082 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006083 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006084 void *oldLockingContext; /* Original lockingcontext to restore on close */
6085 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6086};
6087
drh7ed97b92010-01-20 13:07:21 +00006088/*
6089** The proxy lock file path for the database at dbPath is written into lPath,
6090** which must point to valid, writable memory large enough for a maxLen length
6091** file path.
drh715ff302008-12-03 22:32:44 +00006092*/
drh715ff302008-12-03 22:32:44 +00006093static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6094 int len;
6095 int dbLen;
6096 int i;
6097
6098#ifdef LOCKPROXYDIR
6099 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6100#else
6101# ifdef _CS_DARWIN_USER_TEMP_DIR
6102 {
drh7ed97b92010-01-20 13:07:21 +00006103 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006104 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6105 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006106 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006107 }
drh7ed97b92010-01-20 13:07:21 +00006108 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006109 }
6110# else
6111 len = strlcpy(lPath, "/tmp/", maxLen);
6112# endif
6113#endif
6114
6115 if( lPath[len-1]!='/' ){
6116 len = strlcat(lPath, "/", maxLen);
6117 }
6118
6119 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006120 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006121 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006122 char c = dbPath[i];
6123 lPath[i+len] = (c=='/')?'_':c;
6124 }
6125 lPath[i+len]='\0';
6126 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006127 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006128 return SQLITE_OK;
6129}
6130
drh7ed97b92010-01-20 13:07:21 +00006131/*
6132 ** Creates the lock file and any missing directories in lockPath
6133 */
6134static int proxyCreateLockPath(const char *lockPath){
6135 int i, len;
6136 char buf[MAXPATHLEN];
6137 int start = 0;
6138
6139 assert(lockPath!=NULL);
6140 /* try to create all the intermediate directories */
6141 len = (int)strlen(lockPath);
6142 buf[0] = lockPath[0];
6143 for( i=1; i<len; i++ ){
6144 if( lockPath[i] == '/' && (i - start > 0) ){
6145 /* only mkdir if leaf dir != "." or "/" or ".." */
6146 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6147 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6148 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006149 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006150 int err=errno;
6151 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006152 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006153 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006154 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006155 return err;
6156 }
6157 }
6158 }
6159 start=i+1;
6160 }
6161 buf[i] = lockPath[i];
6162 }
drh308c2a52010-05-14 11:30:18 +00006163 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006164 return 0;
6165}
6166
drh715ff302008-12-03 22:32:44 +00006167/*
6168** Create a new VFS file descriptor (stored in memory obtained from
6169** sqlite3_malloc) and open the file named "path" in the file descriptor.
6170**
6171** The caller is responsible not only for closing the file descriptor
6172** but also for freeing the memory associated with the file descriptor.
6173*/
drh7ed97b92010-01-20 13:07:21 +00006174static int proxyCreateUnixFile(
6175 const char *path, /* path for the new unixFile */
6176 unixFile **ppFile, /* unixFile created and returned by ref */
6177 int islockfile /* if non zero missing dirs will be created */
6178) {
6179 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006180 unixFile *pNew;
6181 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006182 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006183 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006184 int terrno = 0;
6185 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006186
drh7ed97b92010-01-20 13:07:21 +00006187 /* 1. first try to open/create the file
6188 ** 2. if that fails, and this is a lock file (not-conch), try creating
6189 ** the parent directories and then try again.
6190 ** 3. if that fails, try to open the file read-only
6191 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6192 */
6193 pUnused = findReusableFd(path, openFlags);
6194 if( pUnused ){
6195 fd = pUnused->fd;
6196 }else{
6197 pUnused = sqlite3_malloc(sizeof(*pUnused));
6198 if( !pUnused ){
6199 return SQLITE_NOMEM;
6200 }
6201 }
6202 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006203 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006204 terrno = errno;
6205 if( fd<0 && errno==ENOENT && islockfile ){
6206 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006207 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006208 }
6209 }
6210 }
6211 if( fd<0 ){
6212 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006213 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006214 terrno = errno;
6215 }
6216 if( fd<0 ){
6217 if( islockfile ){
6218 return SQLITE_BUSY;
6219 }
6220 switch (terrno) {
6221 case EACCES:
6222 return SQLITE_PERM;
6223 case EIO:
6224 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6225 default:
drh9978c972010-02-23 17:36:32 +00006226 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006227 }
6228 }
6229
6230 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6231 if( pNew==NULL ){
6232 rc = SQLITE_NOMEM;
6233 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006234 }
6235 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006236 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006237 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006238 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006239 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006240 pUnused->fd = fd;
6241 pUnused->flags = openFlags;
6242 pNew->pUnused = pUnused;
6243
drhc02a43a2012-01-10 23:18:38 +00006244 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006245 if( rc==SQLITE_OK ){
6246 *ppFile = pNew;
6247 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006248 }
drh7ed97b92010-01-20 13:07:21 +00006249end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006250 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006251 sqlite3_free(pNew);
6252 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006253 return rc;
6254}
6255
drh7ed97b92010-01-20 13:07:21 +00006256#ifdef SQLITE_TEST
6257/* simulate multiple hosts by creating unique hostid file paths */
6258int sqlite3_hostid_num = 0;
6259#endif
6260
6261#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6262
drh0ab216a2010-07-02 17:10:40 +00006263/* Not always defined in the headers as it ought to be */
6264extern int gethostuuid(uuid_t id, const struct timespec *wait);
6265
drh7ed97b92010-01-20 13:07:21 +00006266/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6267** bytes of writable memory.
6268*/
6269static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006270 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6271 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006272#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6273 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006274 {
6275 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6276 if( gethostuuid(pHostID, &timeout) ){
6277 int err = errno;
6278 if( pError ){
6279 *pError = err;
6280 }
6281 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006282 }
drh7ed97b92010-01-20 13:07:21 +00006283 }
drh3d4435b2011-08-26 20:55:50 +00006284#else
6285 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006286#endif
drh7ed97b92010-01-20 13:07:21 +00006287#ifdef SQLITE_TEST
6288 /* simulate multiple hosts by creating unique hostid file paths */
6289 if( sqlite3_hostid_num != 0){
6290 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6291 }
6292#endif
6293
6294 return SQLITE_OK;
6295}
6296
6297/* The conch file contains the header, host id and lock file path
6298 */
6299#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6300#define PROXY_HEADERLEN 1 /* conch file header length */
6301#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6302#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6303
6304/*
6305** Takes an open conch file, copies the contents to a new path and then moves
6306** it back. The newly created file's file descriptor is assigned to the
6307** conch file structure and finally the original conch file descriptor is
6308** closed. Returns zero if successful.
6309*/
6310static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6311 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6312 unixFile *conchFile = pCtx->conchFile;
6313 char tPath[MAXPATHLEN];
6314 char buf[PROXY_MAXCONCHLEN];
6315 char *cPath = pCtx->conchFilePath;
6316 size_t readLen = 0;
6317 size_t pathLen = 0;
6318 char errmsg[64] = "";
6319 int fd = -1;
6320 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006321 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006322
6323 /* create a new path by replace the trailing '-conch' with '-break' */
6324 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6325 if( pathLen>MAXPATHLEN || pathLen<6 ||
6326 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006327 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006328 goto end_breaklock;
6329 }
6330 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006331 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006332 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006333 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006334 goto end_breaklock;
6335 }
6336 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006337 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006338 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006339 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006340 goto end_breaklock;
6341 }
drhe562be52011-03-02 18:01:10 +00006342 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006343 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006344 goto end_breaklock;
6345 }
6346 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006347 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006348 goto end_breaklock;
6349 }
6350 rc = 0;
6351 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006352 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006353 conchFile->h = fd;
6354 conchFile->openFlags = O_RDWR | O_CREAT;
6355
6356end_breaklock:
6357 if( rc ){
6358 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006359 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006360 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006361 }
6362 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6363 }
6364 return rc;
6365}
6366
6367/* Take the requested lock on the conch file and break a stale lock if the
6368** host id matches.
6369*/
6370static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6371 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6372 unixFile *conchFile = pCtx->conchFile;
6373 int rc = SQLITE_OK;
6374 int nTries = 0;
6375 struct timespec conchModTime;
6376
drh3d4435b2011-08-26 20:55:50 +00006377 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006378 do {
6379 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6380 nTries ++;
6381 if( rc==SQLITE_BUSY ){
6382 /* If the lock failed (busy):
6383 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6384 * 2nd try: fail if the mod time changed or host id is different, wait
6385 * 10 sec and try again
6386 * 3rd try: break the lock unless the mod time has changed.
6387 */
6388 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006389 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006390 pFile->lastErrno = errno;
6391 return SQLITE_IOERR_LOCK;
6392 }
6393
6394 if( nTries==1 ){
6395 conchModTime = buf.st_mtimespec;
6396 usleep(500000); /* wait 0.5 sec and try the lock again*/
6397 continue;
6398 }
6399
6400 assert( nTries>1 );
6401 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6402 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6403 return SQLITE_BUSY;
6404 }
6405
6406 if( nTries==2 ){
6407 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006408 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006409 if( len<0 ){
6410 pFile->lastErrno = errno;
6411 return SQLITE_IOERR_LOCK;
6412 }
6413 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6414 /* don't break the lock if the host id doesn't match */
6415 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6416 return SQLITE_BUSY;
6417 }
6418 }else{
6419 /* don't break the lock on short read or a version mismatch */
6420 return SQLITE_BUSY;
6421 }
6422 usleep(10000000); /* wait 10 sec and try the lock again */
6423 continue;
6424 }
6425
6426 assert( nTries==3 );
6427 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6428 rc = SQLITE_OK;
6429 if( lockType==EXCLUSIVE_LOCK ){
6430 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6431 }
6432 if( !rc ){
6433 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6434 }
6435 }
6436 }
6437 } while( rc==SQLITE_BUSY && nTries<3 );
6438
6439 return rc;
6440}
6441
6442/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006443** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6444** lockPath means that the lockPath in the conch file will be used if the
6445** host IDs match, or a new lock path will be generated automatically
6446** and written to the conch file.
6447*/
6448static int proxyTakeConch(unixFile *pFile){
6449 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6450
drh7ed97b92010-01-20 13:07:21 +00006451 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006452 return SQLITE_OK;
6453 }else{
6454 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006455 uuid_t myHostID;
6456 int pError = 0;
6457 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006458 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006459 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006460 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006461 int createConch = 0;
6462 int hostIdMatch = 0;
6463 int readLen = 0;
6464 int tryOldLockPath = 0;
6465 int forceNewLockPath = 0;
6466
drh308c2a52010-05-14 11:30:18 +00006467 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6468 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006469
drh7ed97b92010-01-20 13:07:21 +00006470 rc = proxyGetHostID(myHostID, &pError);
6471 if( (rc&0xff)==SQLITE_IOERR ){
6472 pFile->lastErrno = pError;
6473 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006474 }
drh7ed97b92010-01-20 13:07:21 +00006475 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006476 if( rc!=SQLITE_OK ){
6477 goto end_takeconch;
6478 }
drh7ed97b92010-01-20 13:07:21 +00006479 /* read the existing conch file */
6480 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6481 if( readLen<0 ){
6482 /* I/O error: lastErrno set by seekAndRead */
6483 pFile->lastErrno = conchFile->lastErrno;
6484 rc = SQLITE_IOERR_READ;
6485 goto end_takeconch;
6486 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6487 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6488 /* a short read or version format mismatch means we need to create a new
6489 ** conch file.
6490 */
6491 createConch = 1;
6492 }
6493 /* if the host id matches and the lock path already exists in the conch
6494 ** we'll try to use the path there, if we can't open that path, we'll
6495 ** retry with a new auto-generated path
6496 */
6497 do { /* in case we need to try again for an :auto: named lock file */
6498
6499 if( !createConch && !forceNewLockPath ){
6500 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6501 PROXY_HOSTIDLEN);
6502 /* if the conch has data compare the contents */
6503 if( !pCtx->lockProxyPath ){
6504 /* for auto-named local lock file, just check the host ID and we'll
6505 ** use the local lock file path that's already in there
6506 */
6507 if( hostIdMatch ){
6508 size_t pathLen = (readLen - PROXY_PATHINDEX);
6509
6510 if( pathLen>=MAXPATHLEN ){
6511 pathLen=MAXPATHLEN-1;
6512 }
6513 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6514 lockPath[pathLen] = 0;
6515 tempLockPath = lockPath;
6516 tryOldLockPath = 1;
6517 /* create a copy of the lock path if the conch is taken */
6518 goto end_takeconch;
6519 }
6520 }else if( hostIdMatch
6521 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6522 readLen-PROXY_PATHINDEX)
6523 ){
6524 /* conch host and lock path match */
6525 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006526 }
drh7ed97b92010-01-20 13:07:21 +00006527 }
6528
6529 /* if the conch isn't writable and doesn't match, we can't take it */
6530 if( (conchFile->openFlags&O_RDWR) == 0 ){
6531 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006532 goto end_takeconch;
6533 }
drh7ed97b92010-01-20 13:07:21 +00006534
6535 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006536 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006537 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6538 tempLockPath = lockPath;
6539 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006540 }
drh7ed97b92010-01-20 13:07:21 +00006541
6542 /* update conch with host and path (this will fail if other process
6543 ** has a shared lock already), if the host id matches, use the big
6544 ** stick.
drh715ff302008-12-03 22:32:44 +00006545 */
drh7ed97b92010-01-20 13:07:21 +00006546 futimes(conchFile->h, NULL);
6547 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006548 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006549 /* We are trying for an exclusive lock but another thread in this
6550 ** same process is still holding a shared lock. */
6551 rc = SQLITE_BUSY;
6552 } else {
6553 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006554 }
drh715ff302008-12-03 22:32:44 +00006555 }else{
drh7ed97b92010-01-20 13:07:21 +00006556 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006557 }
drh7ed97b92010-01-20 13:07:21 +00006558 if( rc==SQLITE_OK ){
6559 char writeBuffer[PROXY_MAXCONCHLEN];
6560 int writeSize = 0;
6561
6562 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6563 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6564 if( pCtx->lockProxyPath!=NULL ){
6565 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6566 }else{
6567 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6568 }
6569 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006570 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006571 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6572 fsync(conchFile->h);
6573 /* If we created a new conch file (not just updated the contents of a
6574 ** valid conch file), try to match the permissions of the database
6575 */
6576 if( rc==SQLITE_OK && createConch ){
6577 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006578 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006579 if( err==0 ){
6580 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6581 S_IROTH|S_IWOTH);
6582 /* try to match the database file R/W permissions, ignore failure */
6583#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006584 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006585#else
drhff812312011-02-23 13:33:46 +00006586 do{
drhe562be52011-03-02 18:01:10 +00006587 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006588 }while( rc==(-1) && errno==EINTR );
6589 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006590 int code = errno;
6591 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6592 cmode, code, strerror(code));
6593 } else {
6594 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6595 }
6596 }else{
6597 int code = errno;
6598 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6599 err, code, strerror(code));
6600#endif
6601 }
drh715ff302008-12-03 22:32:44 +00006602 }
6603 }
drh7ed97b92010-01-20 13:07:21 +00006604 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6605
6606 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006607 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006608 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006609 int fd;
drh7ed97b92010-01-20 13:07:21 +00006610 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006611 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006612 }
6613 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006614 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006615 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006616 if( fd>=0 ){
6617 pFile->h = fd;
6618 }else{
drh9978c972010-02-23 17:36:32 +00006619 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006620 during locking */
6621 }
6622 }
6623 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6624 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6625 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6626 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6627 /* we couldn't create the proxy lock file with the old lock file path
6628 ** so try again via auto-naming
6629 */
6630 forceNewLockPath = 1;
6631 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006632 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006633 }
6634 }
6635 if( rc==SQLITE_OK ){
6636 /* Need to make a copy of path if we extracted the value
6637 ** from the conch file or the path was allocated on the stack
6638 */
6639 if( tempLockPath ){
6640 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6641 if( !pCtx->lockProxyPath ){
6642 rc = SQLITE_NOMEM;
6643 }
6644 }
6645 }
6646 if( rc==SQLITE_OK ){
6647 pCtx->conchHeld = 1;
6648
6649 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6650 afpLockingContext *afpCtx;
6651 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6652 afpCtx->dbPath = pCtx->lockProxyPath;
6653 }
6654 } else {
6655 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6656 }
drh308c2a52010-05-14 11:30:18 +00006657 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6658 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006659 return rc;
drh308c2a52010-05-14 11:30:18 +00006660 } while (1); /* in case we need to retry the :auto: lock file -
6661 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006662 }
6663}
6664
6665/*
6666** If pFile holds a lock on a conch file, then release that lock.
6667*/
6668static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006669 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006670 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6671 unixFile *conchFile; /* Name of the conch file */
6672
6673 pCtx = (proxyLockingContext *)pFile->lockingContext;
6674 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006675 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006676 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006677 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006678 if( pCtx->conchHeld>0 ){
6679 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6680 }
drh715ff302008-12-03 22:32:44 +00006681 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006682 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6683 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006684 return rc;
6685}
6686
6687/*
6688** Given the name of a database file, compute the name of its conch file.
6689** Store the conch filename in memory obtained from sqlite3_malloc().
6690** Make *pConchPath point to the new name. Return SQLITE_OK on success
6691** or SQLITE_NOMEM if unable to obtain memory.
6692**
6693** The caller is responsible for ensuring that the allocated memory
6694** space is eventually freed.
6695**
6696** *pConchPath is set to NULL if a memory allocation error occurs.
6697*/
6698static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6699 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006700 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006701 char *conchPath; /* buffer in which to construct conch name */
6702
6703 /* Allocate space for the conch filename and initialize the name to
6704 ** the name of the original database file. */
6705 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6706 if( conchPath==0 ){
6707 return SQLITE_NOMEM;
6708 }
6709 memcpy(conchPath, dbPath, len+1);
6710
6711 /* now insert a "." before the last / character */
6712 for( i=(len-1); i>=0; i-- ){
6713 if( conchPath[i]=='/' ){
6714 i++;
6715 break;
6716 }
6717 }
6718 conchPath[i]='.';
6719 while ( i<len ){
6720 conchPath[i+1]=dbPath[i];
6721 i++;
6722 }
6723
6724 /* append the "-conch" suffix to the file */
6725 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006726 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006727
6728 return SQLITE_OK;
6729}
6730
6731
6732/* Takes a fully configured proxy locking-style unix file and switches
6733** the local lock file path
6734*/
6735static int switchLockProxyPath(unixFile *pFile, const char *path) {
6736 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6737 char *oldPath = pCtx->lockProxyPath;
6738 int rc = SQLITE_OK;
6739
drh308c2a52010-05-14 11:30:18 +00006740 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006741 return SQLITE_BUSY;
6742 }
6743
6744 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6745 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6746 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6747 return SQLITE_OK;
6748 }else{
6749 unixFile *lockProxy = pCtx->lockProxy;
6750 pCtx->lockProxy=NULL;
6751 pCtx->conchHeld = 0;
6752 if( lockProxy!=NULL ){
6753 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6754 if( rc ) return rc;
6755 sqlite3_free(lockProxy);
6756 }
6757 sqlite3_free(oldPath);
6758 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6759 }
6760
6761 return rc;
6762}
6763
6764/*
6765** pFile is a file that has been opened by a prior xOpen call. dbPath
6766** is a string buffer at least MAXPATHLEN+1 characters in size.
6767**
6768** This routine find the filename associated with pFile and writes it
6769** int dbPath.
6770*/
6771static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006772#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006773 if( pFile->pMethod == &afpIoMethods ){
6774 /* afp style keeps a reference to the db path in the filePath field
6775 ** of the struct */
drhea678832008-12-10 19:26:22 +00006776 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006777 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6778 } else
drh715ff302008-12-03 22:32:44 +00006779#endif
6780 if( pFile->pMethod == &dotlockIoMethods ){
6781 /* dot lock style uses the locking context to store the dot lock
6782 ** file path */
6783 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6784 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6785 }else{
6786 /* all other styles use the locking context to store the db file path */
6787 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006788 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006789 }
6790 return SQLITE_OK;
6791}
6792
6793/*
6794** Takes an already filled in unix file and alters it so all file locking
6795** will be performed on the local proxy lock file. The following fields
6796** are preserved in the locking context so that they can be restored and
6797** the unix structure properly cleaned up at close time:
6798** ->lockingContext
6799** ->pMethod
6800*/
6801static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6802 proxyLockingContext *pCtx;
6803 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6804 char *lockPath=NULL;
6805 int rc = SQLITE_OK;
6806
drh308c2a52010-05-14 11:30:18 +00006807 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006808 return SQLITE_BUSY;
6809 }
6810 proxyGetDbPathForUnixFile(pFile, dbPath);
6811 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6812 lockPath=NULL;
6813 }else{
6814 lockPath=(char *)path;
6815 }
6816
drh308c2a52010-05-14 11:30:18 +00006817 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6818 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006819
6820 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6821 if( pCtx==0 ){
6822 return SQLITE_NOMEM;
6823 }
6824 memset(pCtx, 0, sizeof(*pCtx));
6825
6826 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6827 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006828 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6829 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6830 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6831 ** (c) the file system is read-only, then enable no-locking access.
6832 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6833 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6834 */
6835 struct statfs fsInfo;
6836 struct stat conchInfo;
6837 int goLockless = 0;
6838
drh99ab3b12011-03-02 15:09:07 +00006839 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006840 int err = errno;
6841 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6842 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6843 }
6844 }
6845 if( goLockless ){
6846 pCtx->conchHeld = -1; /* read only FS/ lockless */
6847 rc = SQLITE_OK;
6848 }
6849 }
drh715ff302008-12-03 22:32:44 +00006850 }
6851 if( rc==SQLITE_OK && lockPath ){
6852 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6853 }
6854
6855 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006856 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6857 if( pCtx->dbPath==NULL ){
6858 rc = SQLITE_NOMEM;
6859 }
6860 }
6861 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006862 /* all memory is allocated, proxys are created and assigned,
6863 ** switch the locking context and pMethod then return.
6864 */
drh715ff302008-12-03 22:32:44 +00006865 pCtx->oldLockingContext = pFile->lockingContext;
6866 pFile->lockingContext = pCtx;
6867 pCtx->pOldMethod = pFile->pMethod;
6868 pFile->pMethod = &proxyIoMethods;
6869 }else{
6870 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006871 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006872 sqlite3_free(pCtx->conchFile);
6873 }
drhd56b1212010-08-11 06:14:15 +00006874 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006875 sqlite3_free(pCtx->conchFilePath);
6876 sqlite3_free(pCtx);
6877 }
drh308c2a52010-05-14 11:30:18 +00006878 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6879 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006880 return rc;
6881}
6882
6883
6884/*
6885** This routine handles sqlite3_file_control() calls that are specific
6886** to proxy locking.
6887*/
6888static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6889 switch( op ){
6890 case SQLITE_GET_LOCKPROXYFILE: {
6891 unixFile *pFile = (unixFile*)id;
6892 if( pFile->pMethod == &proxyIoMethods ){
6893 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6894 proxyTakeConch(pFile);
6895 if( pCtx->lockProxyPath ){
6896 *(const char **)pArg = pCtx->lockProxyPath;
6897 }else{
6898 *(const char **)pArg = ":auto: (not held)";
6899 }
6900 } else {
6901 *(const char **)pArg = NULL;
6902 }
6903 return SQLITE_OK;
6904 }
6905 case SQLITE_SET_LOCKPROXYFILE: {
6906 unixFile *pFile = (unixFile*)id;
6907 int rc = SQLITE_OK;
6908 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6909 if( pArg==NULL || (const char *)pArg==0 ){
6910 if( isProxyStyle ){
6911 /* turn off proxy locking - not supported */
6912 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6913 }else{
6914 /* turn off proxy locking - already off - NOOP */
6915 rc = SQLITE_OK;
6916 }
6917 }else{
6918 const char *proxyPath = (const char *)pArg;
6919 if( isProxyStyle ){
6920 proxyLockingContext *pCtx =
6921 (proxyLockingContext*)pFile->lockingContext;
6922 if( !strcmp(pArg, ":auto:")
6923 || (pCtx->lockProxyPath &&
6924 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6925 ){
6926 rc = SQLITE_OK;
6927 }else{
6928 rc = switchLockProxyPath(pFile, proxyPath);
6929 }
6930 }else{
6931 /* turn on proxy file locking */
6932 rc = proxyTransformUnixFile(pFile, proxyPath);
6933 }
6934 }
6935 return rc;
6936 }
6937 default: {
6938 assert( 0 ); /* The call assures that only valid opcodes are sent */
6939 }
6940 }
6941 /*NOTREACHED*/
6942 return SQLITE_ERROR;
6943}
6944
6945/*
6946** Within this division (the proxying locking implementation) the procedures
6947** above this point are all utilities. The lock-related methods of the
6948** proxy-locking sqlite3_io_method object follow.
6949*/
6950
6951
6952/*
6953** This routine checks if there is a RESERVED lock held on the specified
6954** file by this or any other process. If such a lock is held, set *pResOut
6955** to a non-zero value otherwise *pResOut is set to zero. The return value
6956** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6957*/
6958static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6959 unixFile *pFile = (unixFile*)id;
6960 int rc = proxyTakeConch(pFile);
6961 if( rc==SQLITE_OK ){
6962 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006963 if( pCtx->conchHeld>0 ){
6964 unixFile *proxy = pCtx->lockProxy;
6965 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6966 }else{ /* conchHeld < 0 is lockless */
6967 pResOut=0;
6968 }
drh715ff302008-12-03 22:32:44 +00006969 }
6970 return rc;
6971}
6972
6973/*
drh308c2a52010-05-14 11:30:18 +00006974** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006975** of the following:
6976**
6977** (1) SHARED_LOCK
6978** (2) RESERVED_LOCK
6979** (3) PENDING_LOCK
6980** (4) EXCLUSIVE_LOCK
6981**
6982** Sometimes when requesting one lock state, additional lock states
6983** are inserted in between. The locking might fail on one of the later
6984** transitions leaving the lock state different from what it started but
6985** still short of its goal. The following chart shows the allowed
6986** transitions and the inserted intermediate states:
6987**
6988** UNLOCKED -> SHARED
6989** SHARED -> RESERVED
6990** SHARED -> (PENDING) -> EXCLUSIVE
6991** RESERVED -> (PENDING) -> EXCLUSIVE
6992** PENDING -> EXCLUSIVE
6993**
6994** This routine will only increase a lock. Use the sqlite3OsUnlock()
6995** routine to lower a locking level.
6996*/
drh308c2a52010-05-14 11:30:18 +00006997static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006998 unixFile *pFile = (unixFile*)id;
6999 int rc = proxyTakeConch(pFile);
7000 if( rc==SQLITE_OK ){
7001 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007002 if( pCtx->conchHeld>0 ){
7003 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007004 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7005 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007006 }else{
7007 /* conchHeld < 0 is lockless */
7008 }
drh715ff302008-12-03 22:32:44 +00007009 }
7010 return rc;
7011}
7012
7013
7014/*
drh308c2a52010-05-14 11:30:18 +00007015** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007016** must be either NO_LOCK or SHARED_LOCK.
7017**
7018** If the locking level of the file descriptor is already at or below
7019** the requested locking level, this routine is a no-op.
7020*/
drh308c2a52010-05-14 11:30:18 +00007021static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007022 unixFile *pFile = (unixFile*)id;
7023 int rc = proxyTakeConch(pFile);
7024 if( rc==SQLITE_OK ){
7025 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007026 if( pCtx->conchHeld>0 ){
7027 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007028 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7029 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007030 }else{
7031 /* conchHeld < 0 is lockless */
7032 }
drh715ff302008-12-03 22:32:44 +00007033 }
7034 return rc;
7035}
7036
7037/*
7038** Close a file that uses proxy locks.
7039*/
7040static int proxyClose(sqlite3_file *id) {
7041 if( id ){
7042 unixFile *pFile = (unixFile*)id;
7043 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7044 unixFile *lockProxy = pCtx->lockProxy;
7045 unixFile *conchFile = pCtx->conchFile;
7046 int rc = SQLITE_OK;
7047
7048 if( lockProxy ){
7049 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7050 if( rc ) return rc;
7051 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7052 if( rc ) return rc;
7053 sqlite3_free(lockProxy);
7054 pCtx->lockProxy = 0;
7055 }
7056 if( conchFile ){
7057 if( pCtx->conchHeld ){
7058 rc = proxyReleaseConch(pFile);
7059 if( rc ) return rc;
7060 }
7061 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7062 if( rc ) return rc;
7063 sqlite3_free(conchFile);
7064 }
drhd56b1212010-08-11 06:14:15 +00007065 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007066 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007067 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007068 /* restore the original locking context and pMethod then close it */
7069 pFile->lockingContext = pCtx->oldLockingContext;
7070 pFile->pMethod = pCtx->pOldMethod;
7071 sqlite3_free(pCtx);
7072 return pFile->pMethod->xClose(id);
7073 }
7074 return SQLITE_OK;
7075}
7076
7077
7078
drhd2cb50b2009-01-09 21:41:17 +00007079#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007080/*
7081** The proxy locking style is intended for use with AFP filesystems.
7082** And since AFP is only supported on MacOSX, the proxy locking is also
7083** restricted to MacOSX.
7084**
7085**
7086******************* End of the proxy lock implementation **********************
7087******************************************************************************/
7088
drh734c9862008-11-28 15:37:20 +00007089/*
danielk1977e339d652008-06-28 11:23:00 +00007090** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007091**
7092** This routine registers all VFS implementations for unix-like operating
7093** systems. This routine, and the sqlite3_os_end() routine that follows,
7094** should be the only routines in this file that are visible from other
7095** files.
drh6b9d6dd2008-12-03 19:34:47 +00007096**
7097** This routine is called once during SQLite initialization and by a
7098** single thread. The memory allocation and mutex subsystems have not
7099** necessarily been initialized when this routine is called, and so they
7100** should not be used.
drh153c62c2007-08-24 03:51:33 +00007101*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007102int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007103 /*
7104 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007105 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7106 ** to the "finder" function. (pAppData is a pointer to a pointer because
7107 ** silly C90 rules prohibit a void* from being cast to a function pointer
7108 ** and so we have to go through the intermediate pointer to avoid problems
7109 ** when compiling with -pedantic-errors on GCC.)
7110 **
7111 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007112 ** finder-function. The finder-function returns a pointer to the
7113 ** sqlite_io_methods object that implements the desired locking
7114 ** behaviors. See the division above that contains the IOMETHODS
7115 ** macro for addition information on finder-functions.
7116 **
7117 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7118 ** object. But the "autolockIoFinder" available on MacOSX does a little
7119 ** more than that; it looks at the filesystem type that hosts the
7120 ** database file and tries to choose an locking method appropriate for
7121 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007122 */
drh7708e972008-11-29 00:56:52 +00007123 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007124 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007125 sizeof(unixFile), /* szOsFile */ \
7126 MAX_PATHNAME, /* mxPathname */ \
7127 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007128 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007129 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007130 unixOpen, /* xOpen */ \
7131 unixDelete, /* xDelete */ \
7132 unixAccess, /* xAccess */ \
7133 unixFullPathname, /* xFullPathname */ \
7134 unixDlOpen, /* xDlOpen */ \
7135 unixDlError, /* xDlError */ \
7136 unixDlSym, /* xDlSym */ \
7137 unixDlClose, /* xDlClose */ \
7138 unixRandomness, /* xRandomness */ \
7139 unixSleep, /* xSleep */ \
7140 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007141 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007142 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007143 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007144 unixGetSystemCall, /* xGetSystemCall */ \
7145 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007146 }
7147
drh6b9d6dd2008-12-03 19:34:47 +00007148 /*
7149 ** All default VFSes for unix are contained in the following array.
7150 **
7151 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7152 ** by the SQLite core when the VFS is registered. So the following
7153 ** array cannot be const.
7154 */
danielk1977e339d652008-06-28 11:23:00 +00007155 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007156#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007157 UNIXVFS("unix", autolockIoFinder ),
7158#else
7159 UNIXVFS("unix", posixIoFinder ),
7160#endif
7161 UNIXVFS("unix-none", nolockIoFinder ),
7162 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007163 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007164#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007165 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007166#endif
7167#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007168 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007169#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007170 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007171#endif
chw78a13182009-04-07 05:35:03 +00007172#endif
drhd2cb50b2009-01-09 21:41:17 +00007173#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007174 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007175 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007176 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007177#endif
drh153c62c2007-08-24 03:51:33 +00007178 };
drh6b9d6dd2008-12-03 19:34:47 +00007179 unsigned int i; /* Loop counter */
7180
drh2aa5a002011-04-13 13:42:25 +00007181 /* Double-check that the aSyscall[] array has been constructed
7182 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhe1186ab2013-01-04 20:45:13 +00007183 assert( ArraySize(aSyscall)==21 );
drh2aa5a002011-04-13 13:42:25 +00007184
drh6b9d6dd2008-12-03 19:34:47 +00007185 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007186 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007187 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007188 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007189 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007190}
danielk1977e339d652008-06-28 11:23:00 +00007191
7192/*
drh6b9d6dd2008-12-03 19:34:47 +00007193** Shutdown the operating system interface.
7194**
7195** Some operating systems might need to do some cleanup in this routine,
7196** to release dynamically allocated objects. But not on unix.
7197** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007198*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007199int sqlite3_os_end(void){
7200 return SQLITE_OK;
7201}
drhdce8bdb2007-08-16 13:01:44 +00007202
danielk197729bafea2008-06-26 10:41:19 +00007203#endif /* SQLITE_OS_UNIX */