blob: 625f4134062d0eb634093d1ccdd091bfed0dbc19 [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 {
mistachkin48864df2013-03-21 21:20:32 +0000347 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000348 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
dan893c0ff2013-03-25 19:05:07 +0000447 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
448#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
449
drhd1ab8062013-03-25 20:50:25 +0000450 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
451#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
452
453#if defined(__linux__) && defined(_GNU_SOURCE)
454 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
455#else
456 { "mremap", (sqlite3_syscall_ptr)0, 0 },
457#endif
458#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
459
drhe562be52011-03-02 18:01:10 +0000460}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000461
462/*
463** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000464** "unix" VFSes. Return SQLITE_OK opon successfully updating the
465** system call pointer, or SQLITE_NOTFOUND if there is no configurable
466** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000467*/
468static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000469 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
470 const char *zName, /* Name of system call to override */
471 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000472){
drh58ad5802011-03-23 22:02:23 +0000473 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000474 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000475
476 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000477 if( zName==0 ){
478 /* If no zName is given, restore all system calls to their default
479 ** settings and return NULL
480 */
dan51438a72011-04-02 17:00:47 +0000481 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000482 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
483 if( aSyscall[i].pDefault ){
484 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000485 }
486 }
487 }else{
488 /* If zName is specified, operate on only the one system call
489 ** specified.
490 */
491 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
492 if( strcmp(zName, aSyscall[i].zName)==0 ){
493 if( aSyscall[i].pDefault==0 ){
494 aSyscall[i].pDefault = aSyscall[i].pCurrent;
495 }
drh1df30962011-03-02 19:06:42 +0000496 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000497 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
498 aSyscall[i].pCurrent = pNewFunc;
499 break;
500 }
501 }
502 }
503 return rc;
504}
505
drh1df30962011-03-02 19:06:42 +0000506/*
507** Return the value of a system call. Return NULL if zName is not a
508** recognized system call name. NULL is also returned if the system call
509** is currently undefined.
510*/
drh58ad5802011-03-23 22:02:23 +0000511static sqlite3_syscall_ptr unixGetSystemCall(
512 sqlite3_vfs *pNotUsed,
513 const char *zName
514){
515 unsigned int i;
516
517 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000518 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
519 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
520 }
521 return 0;
522}
523
524/*
525** Return the name of the first system call after zName. If zName==NULL
526** then return the name of the first system call. Return NULL if zName
527** is the last system call or if zName is not the name of a valid
528** system call.
529*/
530static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000531 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000532
533 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000534 if( zName ){
535 for(i=0; i<ArraySize(aSyscall)-1; i++){
536 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000537 }
538 }
dan0fd7d862011-03-29 10:04:23 +0000539 for(i++; i<ArraySize(aSyscall); i++){
540 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000541 }
542 return 0;
543}
544
drhad4f1e52011-03-04 15:43:57 +0000545/*
drh8c815d12012-02-13 20:16:37 +0000546** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000547** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000548**
549** If the file creation mode "m" is 0 then set it to the default for
550** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
551** 0644) as modified by the system umask. If m is not 0, then
552** make the file creation mode be exactly m ignoring the umask.
553**
554** The m parameter will be non-zero only when creating -wal, -journal,
555** and -shm files. We want those files to have *exactly* the same
556** permissions as their original database, unadulterated by the umask.
557** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
558** transaction crashes and leaves behind hot journals, then any
559** process that is able to write to the database will also be able to
560** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000561*/
drh8c815d12012-02-13 20:16:37 +0000562static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000563 int fd;
drhe1186ab2013-01-04 20:45:13 +0000564 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5adc60b2012-04-14 13:25:11 +0000565 do{
566#if defined(O_CLOEXEC)
567 fd = osOpen(z,f|O_CLOEXEC,m2);
568#else
569 fd = osOpen(z,f,m2);
570#endif
571 }while( fd<0 && errno==EINTR );
drhe1186ab2013-01-04 20:45:13 +0000572 if( fd>=0 ){
573 if( m!=0 ){
574 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000575 if( osFstat(fd, &statbuf)==0
576 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000577 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000578 ){
drhe1186ab2013-01-04 20:45:13 +0000579 osFchmod(fd, m);
580 }
581 }
drh5adc60b2012-04-14 13:25:11 +0000582#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000583 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000584#endif
drhe1186ab2013-01-04 20:45:13 +0000585 }
drh5adc60b2012-04-14 13:25:11 +0000586 return fd;
drhad4f1e52011-03-04 15:43:57 +0000587}
danielk197713adf8a2004-06-03 16:08:41 +0000588
drh107886a2008-11-21 22:21:50 +0000589/*
dan9359c7b2009-08-21 08:29:10 +0000590** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000591** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000592** vxworksFileId objects used by this file, all of which may be
593** shared by multiple threads.
594**
595** Function unixMutexHeld() is used to assert() that the global mutex
596** is held when required. This function is only used as part of assert()
597** statements. e.g.
598**
599** unixEnterMutex()
600** assert( unixMutexHeld() );
601** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000602*/
603static void unixEnterMutex(void){
604 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
605}
606static void unixLeaveMutex(void){
607 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
608}
dan9359c7b2009-08-21 08:29:10 +0000609#ifdef SQLITE_DEBUG
610static int unixMutexHeld(void) {
611 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
612}
613#endif
drh107886a2008-11-21 22:21:50 +0000614
drh734c9862008-11-28 15:37:20 +0000615
drh30ddce62011-10-15 00:16:30 +0000616#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000617/*
618** Helper function for printing out trace information from debugging
619** binaries. This returns the string represetation of the supplied
620** integer lock-type.
621*/
drh308c2a52010-05-14 11:30:18 +0000622static const char *azFileLock(int eFileLock){
623 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000624 case NO_LOCK: return "NONE";
625 case SHARED_LOCK: return "SHARED";
626 case RESERVED_LOCK: return "RESERVED";
627 case PENDING_LOCK: return "PENDING";
628 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000629 }
630 return "ERROR";
631}
632#endif
633
634#ifdef SQLITE_LOCK_TRACE
635/*
636** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000637**
drh734c9862008-11-28 15:37:20 +0000638** This routine is used for troubleshooting locks on multithreaded
639** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
640** command-line option on the compiler. This code is normally
641** turned off.
642*/
643static int lockTrace(int fd, int op, struct flock *p){
644 char *zOpName, *zType;
645 int s;
646 int savedErrno;
647 if( op==F_GETLK ){
648 zOpName = "GETLK";
649 }else if( op==F_SETLK ){
650 zOpName = "SETLK";
651 }else{
drh99ab3b12011-03-02 15:09:07 +0000652 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000653 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
654 return s;
655 }
656 if( p->l_type==F_RDLCK ){
657 zType = "RDLCK";
658 }else if( p->l_type==F_WRLCK ){
659 zType = "WRLCK";
660 }else if( p->l_type==F_UNLCK ){
661 zType = "UNLCK";
662 }else{
663 assert( 0 );
664 }
665 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000666 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000667 savedErrno = errno;
668 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
669 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
670 (int)p->l_pid, s);
671 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
672 struct flock l2;
673 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000674 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000675 if( l2.l_type==F_RDLCK ){
676 zType = "RDLCK";
677 }else if( l2.l_type==F_WRLCK ){
678 zType = "WRLCK";
679 }else if( l2.l_type==F_UNLCK ){
680 zType = "UNLCK";
681 }else{
682 assert( 0 );
683 }
684 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
685 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
686 }
687 errno = savedErrno;
688 return s;
689}
drh99ab3b12011-03-02 15:09:07 +0000690#undef osFcntl
691#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000692#endif /* SQLITE_LOCK_TRACE */
693
drhff812312011-02-23 13:33:46 +0000694/*
695** Retry ftruncate() calls that fail due to EINTR
696*/
drhff812312011-02-23 13:33:46 +0000697static int robust_ftruncate(int h, sqlite3_int64 sz){
698 int rc;
drh99ab3b12011-03-02 15:09:07 +0000699 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000700 return rc;
701}
drh734c9862008-11-28 15:37:20 +0000702
703/*
704** This routine translates a standard POSIX errno code into something
705** useful to the clients of the sqlite3 functions. Specifically, it is
706** intended to translate a variety of "try again" errors into SQLITE_BUSY
707** and a variety of "please close the file descriptor NOW" errors into
708** SQLITE_IOERR
709**
710** Errors during initialization of locks, or file system support for locks,
711** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
712*/
713static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
714 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000715#if 0
716 /* At one point this code was not commented out. In theory, this branch
717 ** should never be hit, as this function should only be called after
718 ** a locking-related function (i.e. fcntl()) has returned non-zero with
719 ** the value of errno as the first argument. Since a system call has failed,
720 ** errno should be non-zero.
721 **
722 ** Despite this, if errno really is zero, we still don't want to return
723 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
724 ** propagated back to the caller. Commenting this branch out means errno==0
725 ** will be handled by the "default:" case below.
726 */
drh734c9862008-11-28 15:37:20 +0000727 case 0:
728 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000729#endif
730
drh734c9862008-11-28 15:37:20 +0000731 case EAGAIN:
732 case ETIMEDOUT:
733 case EBUSY:
734 case EINTR:
735 case ENOLCK:
736 /* random NFS retry error, unless during file system support
737 * introspection, in which it actually means what it says */
738 return SQLITE_BUSY;
739
740 case EACCES:
741 /* EACCES is like EAGAIN during locking operations, but not any other time*/
742 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000743 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
744 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
745 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000746 return SQLITE_BUSY;
747 }
748 /* else fall through */
749 case EPERM:
750 return SQLITE_PERM;
751
danea83bc62011-04-01 11:56:32 +0000752 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
753 ** this module never makes such a call. And the code in SQLite itself
754 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
755 ** this case is also commented out. If the system does set errno to EDEADLK,
756 ** the default SQLITE_IOERR_XXX code will be returned. */
757#if 0
drh734c9862008-11-28 15:37:20 +0000758 case EDEADLK:
759 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000760#endif
drh734c9862008-11-28 15:37:20 +0000761
762#if EOPNOTSUPP!=ENOTSUP
763 case EOPNOTSUPP:
764 /* something went terribly awry, unless during file system support
765 * introspection, in which it actually means what it says */
766#endif
767#ifdef ENOTSUP
768 case ENOTSUP:
769 /* invalid fd, unless during file system support introspection, in which
770 * it actually means what it says */
771#endif
772 case EIO:
773 case EBADF:
774 case EINVAL:
775 case ENOTCONN:
776 case ENODEV:
777 case ENXIO:
778 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000779#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000780 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000781#endif
drh734c9862008-11-28 15:37:20 +0000782 case ENOSYS:
783 /* these should force the client to close the file and reconnect */
784
785 default:
786 return sqliteIOErr;
787 }
788}
789
790
791
792/******************************************************************************
793****************** Begin Unique File ID Utility Used By VxWorks ***************
794**
795** On most versions of unix, we can get a unique ID for a file by concatenating
796** the device number and the inode number. But this does not work on VxWorks.
797** On VxWorks, a unique file id must be based on the canonical filename.
798**
799** A pointer to an instance of the following structure can be used as a
800** unique file ID in VxWorks. Each instance of this structure contains
801** a copy of the canonical filename. There is also a reference count.
802** The structure is reclaimed when the number of pointers to it drops to
803** zero.
804**
805** There are never very many files open at one time and lookups are not
806** a performance-critical path, so it is sufficient to put these
807** structures on a linked list.
808*/
809struct vxworksFileId {
810 struct vxworksFileId *pNext; /* Next in a list of them all */
811 int nRef; /* Number of references to this one */
812 int nName; /* Length of the zCanonicalName[] string */
813 char *zCanonicalName; /* Canonical filename */
814};
815
816#if OS_VXWORKS
817/*
drh9b35ea62008-11-29 02:20:26 +0000818** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000819** variable:
820*/
821static struct vxworksFileId *vxworksFileList = 0;
822
823/*
824** Simplify a filename into its canonical form
825** by making the following changes:
826**
827** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000828** * convert /./ into just /
829** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000830**
831** Changes are made in-place. Return the new name length.
832**
833** The original filename is in z[0..n-1]. Return the number of
834** characters in the simplified name.
835*/
836static int vxworksSimplifyName(char *z, int n){
837 int i, j;
838 while( n>1 && z[n-1]=='/' ){ n--; }
839 for(i=j=0; i<n; i++){
840 if( z[i]=='/' ){
841 if( z[i+1]=='/' ) continue;
842 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
843 i += 1;
844 continue;
845 }
846 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
847 while( j>0 && z[j-1]!='/' ){ j--; }
848 if( j>0 ){ j--; }
849 i += 2;
850 continue;
851 }
852 }
853 z[j++] = z[i];
854 }
855 z[j] = 0;
856 return j;
857}
858
859/*
860** Find a unique file ID for the given absolute pathname. Return
861** a pointer to the vxworksFileId object. This pointer is the unique
862** file ID.
863**
864** The nRef field of the vxworksFileId object is incremented before
865** the object is returned. A new vxworksFileId object is created
866** and added to the global list if necessary.
867**
868** If a memory allocation error occurs, return NULL.
869*/
870static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
871 struct vxworksFileId *pNew; /* search key and new file ID */
872 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
873 int n; /* Length of zAbsoluteName string */
874
875 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000876 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000877 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
878 if( pNew==0 ) return 0;
879 pNew->zCanonicalName = (char*)&pNew[1];
880 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
881 n = vxworksSimplifyName(pNew->zCanonicalName, n);
882
883 /* Search for an existing entry that matching the canonical name.
884 ** If found, increment the reference count and return a pointer to
885 ** the existing file ID.
886 */
887 unixEnterMutex();
888 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
889 if( pCandidate->nName==n
890 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
891 ){
892 sqlite3_free(pNew);
893 pCandidate->nRef++;
894 unixLeaveMutex();
895 return pCandidate;
896 }
897 }
898
899 /* No match was found. We will make a new file ID */
900 pNew->nRef = 1;
901 pNew->nName = n;
902 pNew->pNext = vxworksFileList;
903 vxworksFileList = pNew;
904 unixLeaveMutex();
905 return pNew;
906}
907
908/*
909** Decrement the reference count on a vxworksFileId object. Free
910** the object when the reference count reaches zero.
911*/
912static void vxworksReleaseFileId(struct vxworksFileId *pId){
913 unixEnterMutex();
914 assert( pId->nRef>0 );
915 pId->nRef--;
916 if( pId->nRef==0 ){
917 struct vxworksFileId **pp;
918 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
919 assert( *pp==pId );
920 *pp = pId->pNext;
921 sqlite3_free(pId);
922 }
923 unixLeaveMutex();
924}
925#endif /* OS_VXWORKS */
926/*************** End of Unique File ID Utility Used By VxWorks ****************
927******************************************************************************/
928
929
930/******************************************************************************
931*************************** Posix Advisory Locking ****************************
932**
drh9b35ea62008-11-29 02:20:26 +0000933** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000934** section 6.5.2.2 lines 483 through 490 specify that when a process
935** sets or clears a lock, that operation overrides any prior locks set
936** by the same process. It does not explicitly say so, but this implies
937** that it overrides locks set by the same process using a different
938** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000939**
940** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000941** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
942**
943** Suppose ./file1 and ./file2 are really the same file (because
944** one is a hard or symbolic link to the other) then if you set
945** an exclusive lock on fd1, then try to get an exclusive lock
946** on fd2, it works. I would have expected the second lock to
947** fail since there was already a lock on the file due to fd1.
948** But not so. Since both locks came from the same process, the
949** second overrides the first, even though they were on different
950** file descriptors opened on different file names.
951**
drh734c9862008-11-28 15:37:20 +0000952** This means that we cannot use POSIX locks to synchronize file access
953** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000954** to synchronize access for threads in separate processes, but not
955** threads within the same process.
956**
957** To work around the problem, SQLite has to manage file locks internally
958** on its own. Whenever a new database is opened, we have to find the
959** specific inode of the database file (the inode is determined by the
960** st_dev and st_ino fields of the stat structure that fstat() fills in)
961** and check for locks already existing on that inode. When locks are
962** created or removed, we have to look at our own internal record of the
963** locks to see if another thread has previously set a lock on that same
964** inode.
965**
drh9b35ea62008-11-29 02:20:26 +0000966** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
967** For VxWorks, we have to use the alternative unique ID system based on
968** canonical filename and implemented in the previous division.)
969**
danielk1977ad94b582007-08-20 06:44:22 +0000970** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000971** descriptor. It is now a structure that holds the integer file
972** descriptor and a pointer to a structure that describes the internal
973** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000974** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000975** point to the same locking structure. The locking structure keeps
976** a reference count (so we will know when to delete it) and a "cnt"
977** field that tells us its internal lock status. cnt==0 means the
978** file is unlocked. cnt==-1 means the file has an exclusive lock.
979** cnt>0 means there are cnt shared locks on the file.
980**
981** Any attempt to lock or unlock a file first checks the locking
982** structure. The fcntl() system call is only invoked to set a
983** POSIX lock if the internal lock structure transitions between
984** a locked and an unlocked state.
985**
drh734c9862008-11-28 15:37:20 +0000986** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000987**
988** If you close a file descriptor that points to a file that has locks,
989** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000990** released. To work around this problem, each unixInodeInfo object
991** maintains a count of the number of pending locks on tha inode.
992** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000993** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000994** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000995** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000996** be closed and that list is walked (and cleared) when the last lock
997** clears.
998**
drh9b35ea62008-11-29 02:20:26 +0000999** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001000**
drh9b35ea62008-11-29 02:20:26 +00001001** Many older versions of linux use the LinuxThreads library which is
1002** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001003** A cannot be modified or overridden by a different thread B.
1004** Only thread A can modify the lock. Locking behavior is correct
1005** if the appliation uses the newer Native Posix Thread Library (NPTL)
1006** on linux - with NPTL a lock created by thread A can override locks
1007** in thread B. But there is no way to know at compile-time which
1008** threading library is being used. So there is no way to know at
1009** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001010** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001011** current process.
drh5fdae772004-06-29 03:29:00 +00001012**
drh8af6c222010-05-14 12:43:01 +00001013** SQLite used to support LinuxThreads. But support for LinuxThreads
1014** was dropped beginning with version 3.7.0. SQLite will still work with
1015** LinuxThreads provided that (1) there is no more than one connection
1016** per database file in the same process and (2) database connections
1017** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001018*/
1019
1020/*
1021** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001022** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001023*/
1024struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001025 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001026#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001027 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001028#else
drh107886a2008-11-21 22:21:50 +00001029 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001030#endif
1031};
1032
1033/*
drhbbd42a62004-05-22 17:41:58 +00001034** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001035** inode. Or, on LinuxThreads, there is one of these structures for
1036** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001037**
danielk1977ad94b582007-08-20 06:44:22 +00001038** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001039** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001040** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001041*/
drh8af6c222010-05-14 12:43:01 +00001042struct unixInodeInfo {
1043 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001044 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001045 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1046 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001047 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001048 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1049 int nLock; /* Number of outstanding file locks */
1050 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1051 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1052 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001053#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001054 unsigned long long sharedByte; /* for AFP simulated shared lock */
1055#endif
drh6c7d5c52008-11-21 20:32:33 +00001056#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001057 sem_t *pSem; /* Named POSIX semaphore */
1058 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001059#endif
drhbbd42a62004-05-22 17:41:58 +00001060};
1061
drhda0e7682008-07-30 15:27:54 +00001062/*
drh8af6c222010-05-14 12:43:01 +00001063** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001064*/
drhd91c68f2010-05-14 14:52:25 +00001065static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001066
drh5fdae772004-06-29 03:29:00 +00001067/*
dane18d4952011-02-21 11:46:24 +00001068**
1069** This function - unixLogError_x(), is only ever called via the macro
1070** unixLogError().
1071**
1072** It is invoked after an error occurs in an OS function and errno has been
1073** set. It logs a message using sqlite3_log() containing the current value of
1074** errno and, if possible, the human-readable equivalent from strerror() or
1075** strerror_r().
1076**
1077** The first argument passed to the macro should be the error code that
1078** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1079** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001080** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001081** if any.
1082*/
drh0e9365c2011-03-02 02:08:13 +00001083#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1084static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001085 int errcode, /* SQLite error code */
1086 const char *zFunc, /* Name of OS function that failed */
1087 const char *zPath, /* File path associated with error */
1088 int iLine /* Source line number where error occurred */
1089){
1090 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001091 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001092
1093 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1094 ** the strerror() function to obtain the human-readable error message
1095 ** equivalent to errno. Otherwise, use strerror_r().
1096 */
1097#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1098 char aErr[80];
1099 memset(aErr, 0, sizeof(aErr));
1100 zErr = aErr;
1101
1102 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001103 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001104 ** returns a pointer to a buffer containing the error message. That pointer
1105 ** may point to aErr[], or it may point to some static storage somewhere.
1106 ** Otherwise, assume that the system provides the POSIX version of
1107 ** strerror_r(), which always writes an error message into aErr[].
1108 **
1109 ** If the code incorrectly assumes that it is the POSIX version that is
1110 ** available, the error message will often be an empty string. Not a
1111 ** huge problem. Incorrectly concluding that the GNU version is available
1112 ** could lead to a segfault though.
1113 */
1114#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1115 zErr =
1116# endif
drh0e9365c2011-03-02 02:08:13 +00001117 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001118
1119#elif SQLITE_THREADSAFE
1120 /* This is a threadsafe build, but strerror_r() is not available. */
1121 zErr = "";
1122#else
1123 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001124 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001125#endif
1126
1127 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001128 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001129 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001130 "os_unix.c:%d: (%d) %s(%s) - %s",
1131 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001132 );
1133
1134 return errcode;
1135}
1136
drh0e9365c2011-03-02 02:08:13 +00001137/*
1138** Close a file descriptor.
1139**
1140** We assume that close() almost always works, since it is only in a
1141** very sick application or on a very sick platform that it might fail.
1142** If it does fail, simply leak the file descriptor, but do log the
1143** error.
1144**
1145** Note that it is not safe to retry close() after EINTR since the
1146** file descriptor might have already been reused by another thread.
1147** So we don't even try to recover from an EINTR. Just log the error
1148** and move on.
1149*/
1150static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001151 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001152 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1153 pFile ? pFile->zPath : 0, lineno);
1154 }
1155}
dane18d4952011-02-21 11:46:24 +00001156
1157/*
danb0ac3e32010-06-16 10:55:42 +00001158** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001159*/
drh0e9365c2011-03-02 02:08:13 +00001160static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001161 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001162 UnixUnusedFd *p;
1163 UnixUnusedFd *pNext;
1164 for(p=pInode->pUnused; p; p=pNext){
1165 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001166 robust_close(pFile, p->fd, __LINE__);
1167 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001168 }
drh0e9365c2011-03-02 02:08:13 +00001169 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001170}
1171
1172/*
drh8af6c222010-05-14 12:43:01 +00001173** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001174**
1175** The mutex entered using the unixEnterMutex() function must be held
1176** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001177*/
danb0ac3e32010-06-16 10:55:42 +00001178static void releaseInodeInfo(unixFile *pFile){
1179 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001180 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001181 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001182 pInode->nRef--;
1183 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001184 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001185 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001186 if( pInode->pPrev ){
1187 assert( pInode->pPrev->pNext==pInode );
1188 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001189 }else{
drh8af6c222010-05-14 12:43:01 +00001190 assert( inodeList==pInode );
1191 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001192 }
drh8af6c222010-05-14 12:43:01 +00001193 if( pInode->pNext ){
1194 assert( pInode->pNext->pPrev==pInode );
1195 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001196 }
drh8af6c222010-05-14 12:43:01 +00001197 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001198 }
drhbbd42a62004-05-22 17:41:58 +00001199 }
1200}
1201
1202/*
drh8af6c222010-05-14 12:43:01 +00001203** Given a file descriptor, locate the unixInodeInfo object that
1204** describes that file descriptor. Create a new one if necessary. The
1205** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001206**
dan9359c7b2009-08-21 08:29:10 +00001207** The mutex entered using the unixEnterMutex() function must be held
1208** when this function is called.
1209**
drh6c7d5c52008-11-21 20:32:33 +00001210** Return an appropriate error code.
1211*/
drh8af6c222010-05-14 12:43:01 +00001212static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001213 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001214 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001215){
1216 int rc; /* System call return code */
1217 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001218 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1219 struct stat statbuf; /* Low-level file information */
1220 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001221
dan9359c7b2009-08-21 08:29:10 +00001222 assert( unixMutexHeld() );
1223
drh6c7d5c52008-11-21 20:32:33 +00001224 /* Get low-level information about the file that we can used to
1225 ** create a unique name for the file.
1226 */
1227 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001228 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001229 if( rc!=0 ){
1230 pFile->lastErrno = errno;
1231#ifdef EOVERFLOW
1232 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1233#endif
1234 return SQLITE_IOERR;
1235 }
1236
drheb0d74f2009-02-03 15:27:02 +00001237#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001238 /* On OS X on an msdos filesystem, the inode number is reported
1239 ** incorrectly for zero-size files. See ticket #3260. To work
1240 ** around this problem (we consider it a bug in OS X, not SQLite)
1241 ** we always increase the file size to 1 by writing a single byte
1242 ** prior to accessing the inode number. The one byte written is
1243 ** an ASCII 'S' character which also happens to be the first byte
1244 ** in the header of every SQLite database. In this way, if there
1245 ** is a race condition such that another thread has already populated
1246 ** the first page of the database, no damage is done.
1247 */
drh7ed97b92010-01-20 13:07:21 +00001248 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001249 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001250 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001251 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001252 return SQLITE_IOERR;
1253 }
drh99ab3b12011-03-02 15:09:07 +00001254 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001255 if( rc!=0 ){
1256 pFile->lastErrno = errno;
1257 return SQLITE_IOERR;
1258 }
1259 }
drheb0d74f2009-02-03 15:27:02 +00001260#endif
drh6c7d5c52008-11-21 20:32:33 +00001261
drh8af6c222010-05-14 12:43:01 +00001262 memset(&fileId, 0, sizeof(fileId));
1263 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001264#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001265 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001266#else
drh8af6c222010-05-14 12:43:01 +00001267 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001268#endif
drh8af6c222010-05-14 12:43:01 +00001269 pInode = inodeList;
1270 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1271 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001272 }
drh8af6c222010-05-14 12:43:01 +00001273 if( pInode==0 ){
1274 pInode = sqlite3_malloc( sizeof(*pInode) );
1275 if( pInode==0 ){
1276 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001277 }
drh8af6c222010-05-14 12:43:01 +00001278 memset(pInode, 0, sizeof(*pInode));
1279 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1280 pInode->nRef = 1;
1281 pInode->pNext = inodeList;
1282 pInode->pPrev = 0;
1283 if( inodeList ) inodeList->pPrev = pInode;
1284 inodeList = pInode;
1285 }else{
1286 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001287 }
drh8af6c222010-05-14 12:43:01 +00001288 *ppInode = pInode;
1289 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001290}
drh6c7d5c52008-11-21 20:32:33 +00001291
aswift5b1a2562008-08-22 00:22:35 +00001292
1293/*
danielk197713adf8a2004-06-03 16:08:41 +00001294** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001295** file by this or any other process. If such a lock is held, set *pResOut
1296** to a non-zero value otherwise *pResOut is set to zero. The return value
1297** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001298*/
danielk1977861f7452008-06-05 11:39:11 +00001299static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001300 int rc = SQLITE_OK;
1301 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001302 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001303
danielk1977861f7452008-06-05 11:39:11 +00001304 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1305
drh054889e2005-11-30 03:20:31 +00001306 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001307 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001308
1309 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001310 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001311 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001312 }
1313
drh2ac3ee92004-06-07 16:27:46 +00001314 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001315 */
danielk197709480a92009-02-09 05:32:32 +00001316#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001317 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001318 struct flock lock;
1319 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001320 lock.l_start = RESERVED_BYTE;
1321 lock.l_len = 1;
1322 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001323 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1324 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1325 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001326 } else if( lock.l_type!=F_UNLCK ){
1327 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001328 }
1329 }
danielk197709480a92009-02-09 05:32:32 +00001330#endif
danielk197713adf8a2004-06-03 16:08:41 +00001331
drh6c7d5c52008-11-21 20:32:33 +00001332 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001333 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001334
aswift5b1a2562008-08-22 00:22:35 +00001335 *pResOut = reserved;
1336 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001337}
1338
1339/*
drha7e61d82011-03-12 17:02:57 +00001340** Attempt to set a system-lock on the file pFile. The lock is
1341** described by pLock.
1342**
drh77197112011-03-15 19:08:48 +00001343** If the pFile was opened read/write from unix-excl, then the only lock
1344** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001345** the first time any lock is attempted. All subsequent system locking
1346** operations become no-ops. Locking operations still happen internally,
1347** in order to coordinate access between separate database connections
1348** within this process, but all of that is handled in memory and the
1349** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001350**
1351** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1352** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1353** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001354**
1355** Zero is returned if the call completes successfully, or -1 if a call
1356** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001357*/
1358static int unixFileLock(unixFile *pFile, struct flock *pLock){
1359 int rc;
drh3cb93392011-03-12 18:10:44 +00001360 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001361 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001362 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001363 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1364 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1365 ){
drh3cb93392011-03-12 18:10:44 +00001366 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001367 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001368 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001369 lock.l_whence = SEEK_SET;
1370 lock.l_start = SHARED_FIRST;
1371 lock.l_len = SHARED_SIZE;
1372 lock.l_type = F_WRLCK;
1373 rc = osFcntl(pFile->h, F_SETLK, &lock);
1374 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001375 pInode->bProcessLock = 1;
1376 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001377 }else{
1378 rc = 0;
1379 }
1380 }else{
1381 rc = osFcntl(pFile->h, F_SETLK, pLock);
1382 }
1383 return rc;
1384}
1385
1386/*
drh308c2a52010-05-14 11:30:18 +00001387** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001388** of the following:
1389**
drh2ac3ee92004-06-07 16:27:46 +00001390** (1) SHARED_LOCK
1391** (2) RESERVED_LOCK
1392** (3) PENDING_LOCK
1393** (4) EXCLUSIVE_LOCK
1394**
drhb3e04342004-06-08 00:47:47 +00001395** Sometimes when requesting one lock state, additional lock states
1396** are inserted in between. The locking might fail on one of the later
1397** transitions leaving the lock state different from what it started but
1398** still short of its goal. The following chart shows the allowed
1399** transitions and the inserted intermediate states:
1400**
1401** UNLOCKED -> SHARED
1402** SHARED -> RESERVED
1403** SHARED -> (PENDING) -> EXCLUSIVE
1404** RESERVED -> (PENDING) -> EXCLUSIVE
1405** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001406**
drha6abd042004-06-09 17:37:22 +00001407** This routine will only increase a lock. Use the sqlite3OsUnlock()
1408** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001409*/
drh308c2a52010-05-14 11:30:18 +00001410static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001411 /* The following describes the implementation of the various locks and
1412 ** lock transitions in terms of the POSIX advisory shared and exclusive
1413 ** lock primitives (called read-locks and write-locks below, to avoid
1414 ** confusion with SQLite lock names). The algorithms are complicated
1415 ** slightly in order to be compatible with windows systems simultaneously
1416 ** accessing the same database file, in case that is ever required.
1417 **
1418 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1419 ** byte', each single bytes at well known offsets, and the 'shared byte
1420 ** range', a range of 510 bytes at a well known offset.
1421 **
1422 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1423 ** byte'. If this is successful, a random byte from the 'shared byte
1424 ** range' is read-locked and the lock on the 'pending byte' released.
1425 **
danielk197790ba3bd2004-06-25 08:32:25 +00001426 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1427 ** A RESERVED lock is implemented by grabbing a write-lock on the
1428 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001429 **
1430 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001431 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1432 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1433 ** obtained, but existing SHARED locks are allowed to persist. A process
1434 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1435 ** This property is used by the algorithm for rolling back a journal file
1436 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001437 **
danielk197790ba3bd2004-06-25 08:32:25 +00001438 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1439 ** implemented by obtaining a write-lock on the entire 'shared byte
1440 ** range'. Since all other locks require a read-lock on one of the bytes
1441 ** within this range, this ensures that no other locks are held on the
1442 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001443 **
1444 ** The reason a single byte cannot be used instead of the 'shared byte
1445 ** range' is that some versions of windows do not support read-locks. By
1446 ** locking a random byte from a range, concurrent SHARED locks may exist
1447 ** even if the locking primitive used is always a write-lock.
1448 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001449 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001450 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001451 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001452 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001453 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001454
drh054889e2005-11-30 03:20:31 +00001455 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001456 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1457 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001458 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001459
1460 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001461 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001462 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001463 */
drh308c2a52010-05-14 11:30:18 +00001464 if( pFile->eFileLock>=eFileLock ){
1465 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1466 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001467 return SQLITE_OK;
1468 }
1469
drh0c2694b2009-09-03 16:23:44 +00001470 /* Make sure the locking sequence is correct.
1471 ** (1) We never move from unlocked to anything higher than shared lock.
1472 ** (2) SQLite never explicitly requests a pendig lock.
1473 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001474 */
drh308c2a52010-05-14 11:30:18 +00001475 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1476 assert( eFileLock!=PENDING_LOCK );
1477 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001478
drh8af6c222010-05-14 12:43:01 +00001479 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001480 */
drh6c7d5c52008-11-21 20:32:33 +00001481 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001482 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001483
danielk1977ad94b582007-08-20 06:44:22 +00001484 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001485 ** handle that precludes the requested lock, return BUSY.
1486 */
drh8af6c222010-05-14 12:43:01 +00001487 if( (pFile->eFileLock!=pInode->eFileLock &&
1488 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001489 ){
1490 rc = SQLITE_BUSY;
1491 goto end_lock;
1492 }
1493
1494 /* If a SHARED lock is requested, and some thread using this PID already
1495 ** has a SHARED or RESERVED lock, then increment reference counts and
1496 ** return SQLITE_OK.
1497 */
drh308c2a52010-05-14 11:30:18 +00001498 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001499 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001500 assert( eFileLock==SHARED_LOCK );
1501 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001502 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001503 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001504 pInode->nShared++;
1505 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001506 goto end_lock;
1507 }
1508
danielk19779a1d0ab2004-06-01 14:09:28 +00001509
drh3cde3bb2004-06-12 02:17:14 +00001510 /* A PENDING lock is needed before acquiring a SHARED lock and before
1511 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1512 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001513 */
drh0c2694b2009-09-03 16:23:44 +00001514 lock.l_len = 1L;
1515 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001516 if( eFileLock==SHARED_LOCK
1517 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001518 ){
drh308c2a52010-05-14 11:30:18 +00001519 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001520 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001521 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001522 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001523 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001524 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001525 pFile->lastErrno = tErrno;
1526 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001527 goto end_lock;
1528 }
drh3cde3bb2004-06-12 02:17:14 +00001529 }
1530
1531
1532 /* If control gets to this point, then actually go ahead and make
1533 ** operating system calls for the specified lock.
1534 */
drh308c2a52010-05-14 11:30:18 +00001535 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001536 assert( pInode->nShared==0 );
1537 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001538 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001539
drh2ac3ee92004-06-07 16:27:46 +00001540 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001541 lock.l_start = SHARED_FIRST;
1542 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001543 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001544 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001545 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001546 }
dan661d71a2011-03-30 19:08:03 +00001547
drh2ac3ee92004-06-07 16:27:46 +00001548 /* Drop the temporary PENDING lock */
1549 lock.l_start = PENDING_BYTE;
1550 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001551 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001552 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1553 /* This could happen with a network mount */
1554 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001555 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001556 }
dan661d71a2011-03-30 19:08:03 +00001557
1558 if( rc ){
1559 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001560 pFile->lastErrno = tErrno;
1561 }
dan661d71a2011-03-30 19:08:03 +00001562 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001563 }else{
drh308c2a52010-05-14 11:30:18 +00001564 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001565 pInode->nLock++;
1566 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001567 }
drh8af6c222010-05-14 12:43:01 +00001568 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001569 /* We are trying for an exclusive lock but another thread in this
1570 ** same process is still holding a shared lock. */
1571 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001572 }else{
drh3cde3bb2004-06-12 02:17:14 +00001573 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001574 ** assumed that there is a SHARED or greater lock on the file
1575 ** already.
1576 */
drh308c2a52010-05-14 11:30:18 +00001577 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001578 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001579
1580 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1581 if( eFileLock==RESERVED_LOCK ){
1582 lock.l_start = RESERVED_BYTE;
1583 lock.l_len = 1L;
1584 }else{
1585 lock.l_start = SHARED_FIRST;
1586 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001587 }
dan661d71a2011-03-30 19:08:03 +00001588
1589 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001590 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001591 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001592 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001593 pFile->lastErrno = tErrno;
1594 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001595 }
drhbbd42a62004-05-22 17:41:58 +00001596 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001597
drh8f941bc2009-01-14 23:03:40 +00001598
drhd3d8c042012-05-29 17:02:40 +00001599#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001600 /* Set up the transaction-counter change checking flags when
1601 ** transitioning from a SHARED to a RESERVED lock. The change
1602 ** from SHARED to RESERVED marks the beginning of a normal
1603 ** write operation (not a hot journal rollback).
1604 */
1605 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001606 && pFile->eFileLock<=SHARED_LOCK
1607 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001608 ){
1609 pFile->transCntrChng = 0;
1610 pFile->dbUpdate = 0;
1611 pFile->inNormalWrite = 1;
1612 }
1613#endif
1614
1615
danielk1977ecb2a962004-06-02 06:30:16 +00001616 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001617 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001618 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001619 }else if( eFileLock==EXCLUSIVE_LOCK ){
1620 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001621 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001622 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001623
1624end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001625 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001626 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1627 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001628 return rc;
1629}
1630
1631/*
dan08da86a2009-08-21 17:18:03 +00001632** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001633** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001634*/
1635static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001636 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001637 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001638 p->pNext = pInode->pUnused;
1639 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001640 pFile->h = -1;
1641 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001642}
1643
1644/*
drh308c2a52010-05-14 11:30:18 +00001645** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001646** must be either NO_LOCK or SHARED_LOCK.
1647**
1648** If the locking level of the file descriptor is already at or below
1649** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001650**
1651** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1652** the byte range is divided into 2 parts and the first part is unlocked then
1653** set to a read lock, then the other part is simply unlocked. This works
1654** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1655** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001656*/
drha7e61d82011-03-12 17:02:57 +00001657static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001658 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001659 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001660 struct flock lock;
1661 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001662
drh054889e2005-11-30 03:20:31 +00001663 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001664 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001665 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001666 getpid()));
drha6abd042004-06-09 17:37:22 +00001667
drh308c2a52010-05-14 11:30:18 +00001668 assert( eFileLock<=SHARED_LOCK );
1669 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001670 return SQLITE_OK;
1671 }
drh6c7d5c52008-11-21 20:32:33 +00001672 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001673 pInode = pFile->pInode;
1674 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001675 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001676 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001677
drhd3d8c042012-05-29 17:02:40 +00001678#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001679 /* When reducing a lock such that other processes can start
1680 ** reading the database file again, make sure that the
1681 ** transaction counter was updated if any part of the database
1682 ** file changed. If the transaction counter is not updated,
1683 ** other connections to the same file might not realize that
1684 ** the file has changed and hence might not know to flush their
1685 ** cache. The use of a stale cache can lead to database corruption.
1686 */
drh8f941bc2009-01-14 23:03:40 +00001687 pFile->inNormalWrite = 0;
1688#endif
1689
drh7ed97b92010-01-20 13:07:21 +00001690 /* downgrading to a shared lock on NFS involves clearing the write lock
1691 ** before establishing the readlock - to avoid a race condition we downgrade
1692 ** the lock in 2 blocks, so that part of the range will be covered by a
1693 ** write lock until the rest is covered by a read lock:
1694 ** 1: [WWWWW]
1695 ** 2: [....W]
1696 ** 3: [RRRRW]
1697 ** 4: [RRRR.]
1698 */
drh308c2a52010-05-14 11:30:18 +00001699 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001700
1701#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001702 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001703 assert( handleNFSUnlock==0 );
1704#endif
1705#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001706 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001707 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001708 off_t divSize = SHARED_SIZE - 1;
1709
1710 lock.l_type = F_UNLCK;
1711 lock.l_whence = SEEK_SET;
1712 lock.l_start = SHARED_FIRST;
1713 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001714 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001715 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001716 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001717 if( IS_LOCK_ERROR(rc) ){
1718 pFile->lastErrno = tErrno;
1719 }
1720 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001721 }
drh7ed97b92010-01-20 13:07:21 +00001722 lock.l_type = F_RDLCK;
1723 lock.l_whence = SEEK_SET;
1724 lock.l_start = SHARED_FIRST;
1725 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001726 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001727 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001728 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1729 if( IS_LOCK_ERROR(rc) ){
1730 pFile->lastErrno = tErrno;
1731 }
1732 goto end_unlock;
1733 }
1734 lock.l_type = F_UNLCK;
1735 lock.l_whence = SEEK_SET;
1736 lock.l_start = SHARED_FIRST+divSize;
1737 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001738 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001739 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001740 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001741 if( IS_LOCK_ERROR(rc) ){
1742 pFile->lastErrno = tErrno;
1743 }
1744 goto end_unlock;
1745 }
drh30f776f2011-02-25 03:25:07 +00001746 }else
1747#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1748 {
drh7ed97b92010-01-20 13:07:21 +00001749 lock.l_type = F_RDLCK;
1750 lock.l_whence = SEEK_SET;
1751 lock.l_start = SHARED_FIRST;
1752 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001753 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001754 /* In theory, the call to unixFileLock() cannot fail because another
1755 ** process is holding an incompatible lock. If it does, this
1756 ** indicates that the other process is not following the locking
1757 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1758 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1759 ** an assert to fail). */
1760 rc = SQLITE_IOERR_RDLOCK;
1761 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001762 goto end_unlock;
1763 }
drh9c105bb2004-10-02 20:38:28 +00001764 }
1765 }
drhbbd42a62004-05-22 17:41:58 +00001766 lock.l_type = F_UNLCK;
1767 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001768 lock.l_start = PENDING_BYTE;
1769 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001770 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001771 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001772 }else{
danea83bc62011-04-01 11:56:32 +00001773 rc = SQLITE_IOERR_UNLOCK;
1774 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001775 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001776 }
drhbbd42a62004-05-22 17:41:58 +00001777 }
drh308c2a52010-05-14 11:30:18 +00001778 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001779 /* Decrement the shared lock counter. Release the lock using an
1780 ** OS call only when all threads in this same process have released
1781 ** the lock.
1782 */
drh8af6c222010-05-14 12:43:01 +00001783 pInode->nShared--;
1784 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001785 lock.l_type = F_UNLCK;
1786 lock.l_whence = SEEK_SET;
1787 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001788 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001789 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001790 }else{
danea83bc62011-04-01 11:56:32 +00001791 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001792 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001793 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001794 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001795 }
drha6abd042004-06-09 17:37:22 +00001796 }
1797
drhbbd42a62004-05-22 17:41:58 +00001798 /* Decrement the count of locks against this same file. When the
1799 ** count reaches zero, close any other file descriptors whose close
1800 ** was deferred because of outstanding locks.
1801 */
drh8af6c222010-05-14 12:43:01 +00001802 pInode->nLock--;
1803 assert( pInode->nLock>=0 );
1804 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001805 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001806 }
1807 }
drhf2f105d2012-08-20 15:53:54 +00001808
aswift5b1a2562008-08-22 00:22:35 +00001809end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001810 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001811 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001812 return rc;
drhbbd42a62004-05-22 17:41:58 +00001813}
1814
1815/*
drh308c2a52010-05-14 11:30:18 +00001816** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001817** must be either NO_LOCK or SHARED_LOCK.
1818**
1819** If the locking level of the file descriptor is already at or below
1820** the requested locking level, this routine is a no-op.
1821*/
drh308c2a52010-05-14 11:30:18 +00001822static int unixUnlock(sqlite3_file *id, int eFileLock){
dana1afc742013-03-25 13:50:49 +00001823 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
drha7e61d82011-03-12 17:02:57 +00001824 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001825}
1826
danf23da962013-03-23 21:00:41 +00001827static int unixMapfile(unixFile *pFd, i64 nByte);
1828static void unixUnmapfile(unixFile *pFd);
1829
drh7ed97b92010-01-20 13:07:21 +00001830/*
danielk1977e339d652008-06-28 11:23:00 +00001831** This function performs the parts of the "close file" operation
1832** common to all locking schemes. It closes the directory and file
1833** handles, if they are valid, and sets all fields of the unixFile
1834** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001835**
1836** It is *not* necessary to hold the mutex when this routine is called,
1837** even on VxWorks. A mutex will be acquired on VxWorks by the
1838** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001839*/
1840static int closeUnixFile(sqlite3_file *id){
1841 unixFile *pFile = (unixFile*)id;
danf23da962013-03-23 21:00:41 +00001842 unixUnmapfile(pFile);
dan661d71a2011-03-30 19:08:03 +00001843 if( pFile->h>=0 ){
1844 robust_close(pFile, pFile->h, __LINE__);
1845 pFile->h = -1;
1846 }
1847#if OS_VXWORKS
1848 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001849 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001850 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001851 }
1852 vxworksReleaseFileId(pFile->pId);
1853 pFile->pId = 0;
1854 }
1855#endif
1856 OSTRACE(("CLOSE %-3d\n", pFile->h));
1857 OpenCounter(-1);
1858 sqlite3_free(pFile->pUnused);
1859 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001860 return SQLITE_OK;
1861}
1862
1863/*
danielk1977e3026632004-06-22 11:29:02 +00001864** Close a file.
1865*/
danielk197762079062007-08-15 17:08:46 +00001866static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001867 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001868 unixFile *pFile = (unixFile *)id;
1869 unixUnlock(id, NO_LOCK);
1870 unixEnterMutex();
1871
1872 /* unixFile.pInode is always valid here. Otherwise, a different close
1873 ** routine (e.g. nolockClose()) would be called instead.
1874 */
1875 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1876 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1877 /* If there are outstanding locks, do not actually close the file just
1878 ** yet because that would clear those locks. Instead, add the file
1879 ** descriptor to pInode->pUnused list. It will be automatically closed
1880 ** when the last lock is cleared.
1881 */
1882 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001883 }
dan661d71a2011-03-30 19:08:03 +00001884 releaseInodeInfo(pFile);
1885 rc = closeUnixFile(id);
1886 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001887 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001888}
1889
drh734c9862008-11-28 15:37:20 +00001890/************** End of the posix advisory lock implementation *****************
1891******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001892
drh734c9862008-11-28 15:37:20 +00001893/******************************************************************************
1894****************************** No-op Locking **********************************
1895**
1896** Of the various locking implementations available, this is by far the
1897** simplest: locking is ignored. No attempt is made to lock the database
1898** file for reading or writing.
1899**
1900** This locking mode is appropriate for use on read-only databases
1901** (ex: databases that are burned into CD-ROM, for example.) It can
1902** also be used if the application employs some external mechanism to
1903** prevent simultaneous access of the same database by two or more
1904** database connections. But there is a serious risk of database
1905** corruption if this locking mode is used in situations where multiple
1906** database connections are accessing the same database file at the same
1907** time and one or more of those connections are writing.
1908*/
drhbfe66312006-10-03 17:40:40 +00001909
drh734c9862008-11-28 15:37:20 +00001910static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1911 UNUSED_PARAMETER(NotUsed);
1912 *pResOut = 0;
1913 return SQLITE_OK;
1914}
drh734c9862008-11-28 15:37:20 +00001915static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1916 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1917 return SQLITE_OK;
1918}
drh734c9862008-11-28 15:37:20 +00001919static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1920 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1921 return SQLITE_OK;
1922}
1923
1924/*
drh9b35ea62008-11-29 02:20:26 +00001925** Close the file.
drh734c9862008-11-28 15:37:20 +00001926*/
1927static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001928 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001929}
1930
1931/******************* End of the no-op lock implementation *********************
1932******************************************************************************/
1933
1934/******************************************************************************
1935************************* Begin dot-file Locking ******************************
1936**
mistachkin48864df2013-03-21 21:20:32 +00001937** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001938** files (really a directory) to control access to the database. This works
1939** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001940**
1941** (1) There is zero concurrency. A single reader blocks all other
1942** connections from reading or writing the database.
1943**
1944** (2) An application crash or power loss can leave stale lock files
1945** sitting around that need to be cleared manually.
1946**
1947** Nevertheless, a dotlock is an appropriate locking mode for use if no
1948** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001949**
drh9ef6bc42011-11-04 02:24:02 +00001950** Dotfile locking works by creating a subdirectory in the same directory as
1951** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00001952** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00001953** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001954*/
1955
1956/*
1957** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001958** lock directory.
drh734c9862008-11-28 15:37:20 +00001959*/
1960#define DOTLOCK_SUFFIX ".lock"
1961
drh7708e972008-11-29 00:56:52 +00001962/*
1963** This routine checks if there is a RESERVED lock held on the specified
1964** file by this or any other process. If such a lock is held, set *pResOut
1965** to a non-zero value otherwise *pResOut is set to zero. The return value
1966** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1967**
1968** In dotfile locking, either a lock exists or it does not. So in this
1969** variation of CheckReservedLock(), *pResOut is set to true if any lock
1970** is held on the file and false if the file is unlocked.
1971*/
drh734c9862008-11-28 15:37:20 +00001972static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1973 int rc = SQLITE_OK;
1974 int reserved = 0;
1975 unixFile *pFile = (unixFile*)id;
1976
1977 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1978
1979 assert( pFile );
1980
1981 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001982 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001983 /* Either this connection or some other connection in the same process
1984 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001985 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001986 }else{
1987 /* The lock is held if and only if the lockfile exists */
1988 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001989 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001990 }
drh308c2a52010-05-14 11:30:18 +00001991 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001992 *pResOut = reserved;
1993 return rc;
1994}
1995
drh7708e972008-11-29 00:56:52 +00001996/*
drh308c2a52010-05-14 11:30:18 +00001997** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001998** of the following:
1999**
2000** (1) SHARED_LOCK
2001** (2) RESERVED_LOCK
2002** (3) PENDING_LOCK
2003** (4) EXCLUSIVE_LOCK
2004**
2005** Sometimes when requesting one lock state, additional lock states
2006** are inserted in between. The locking might fail on one of the later
2007** transitions leaving the lock state different from what it started but
2008** still short of its goal. The following chart shows the allowed
2009** transitions and the inserted intermediate states:
2010**
2011** UNLOCKED -> SHARED
2012** SHARED -> RESERVED
2013** SHARED -> (PENDING) -> EXCLUSIVE
2014** RESERVED -> (PENDING) -> EXCLUSIVE
2015** PENDING -> EXCLUSIVE
2016**
2017** This routine will only increase a lock. Use the sqlite3OsUnlock()
2018** routine to lower a locking level.
2019**
2020** With dotfile locking, we really only support state (4): EXCLUSIVE.
2021** But we track the other locking levels internally.
2022*/
drh308c2a52010-05-14 11:30:18 +00002023static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002024 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002025 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002026 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002027
drh7708e972008-11-29 00:56:52 +00002028
2029 /* If we have any lock, then the lock file already exists. All we have
2030 ** to do is adjust our internal record of the lock level.
2031 */
drh308c2a52010-05-14 11:30:18 +00002032 if( pFile->eFileLock > NO_LOCK ){
2033 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002034 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002035#ifdef HAVE_UTIME
2036 utime(zLockFile, NULL);
2037#else
drh734c9862008-11-28 15:37:20 +00002038 utimes(zLockFile, NULL);
2039#endif
drh7708e972008-11-29 00:56:52 +00002040 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002041 }
2042
2043 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002044 rc = osMkdir(zLockFile, 0777);
2045 if( rc<0 ){
2046 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002047 int tErrno = errno;
2048 if( EEXIST == tErrno ){
2049 rc = SQLITE_BUSY;
2050 } else {
2051 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2052 if( IS_LOCK_ERROR(rc) ){
2053 pFile->lastErrno = tErrno;
2054 }
2055 }
drh7708e972008-11-29 00:56:52 +00002056 return rc;
drh734c9862008-11-28 15:37:20 +00002057 }
drh734c9862008-11-28 15:37:20 +00002058
2059 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002060 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002061 return rc;
2062}
2063
drh7708e972008-11-29 00:56:52 +00002064/*
drh308c2a52010-05-14 11:30:18 +00002065** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002066** must be either NO_LOCK or SHARED_LOCK.
2067**
2068** If the locking level of the file descriptor is already at or below
2069** the requested locking level, this routine is a no-op.
2070**
2071** When the locking level reaches NO_LOCK, delete the lock file.
2072*/
drh308c2a52010-05-14 11:30:18 +00002073static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002074 unixFile *pFile = (unixFile*)id;
2075 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002076 int rc;
drh734c9862008-11-28 15:37:20 +00002077
2078 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002079 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002080 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002081 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002082
2083 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002084 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002085 return SQLITE_OK;
2086 }
drh7708e972008-11-29 00:56:52 +00002087
2088 /* To downgrade to shared, simply update our internal notion of the
2089 ** lock state. No need to mess with the file on disk.
2090 */
drh308c2a52010-05-14 11:30:18 +00002091 if( eFileLock==SHARED_LOCK ){
2092 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002093 return SQLITE_OK;
2094 }
2095
drh7708e972008-11-29 00:56:52 +00002096 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002097 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002098 rc = osRmdir(zLockFile);
2099 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2100 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002101 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002102 rc = 0;
drh734c9862008-11-28 15:37:20 +00002103 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002104 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002105 }
2106 if( IS_LOCK_ERROR(rc) ){
2107 pFile->lastErrno = tErrno;
2108 }
2109 return rc;
2110 }
drh308c2a52010-05-14 11:30:18 +00002111 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002112 return SQLITE_OK;
2113}
2114
2115/*
drh9b35ea62008-11-29 02:20:26 +00002116** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002117*/
2118static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002119 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002120 if( id ){
2121 unixFile *pFile = (unixFile*)id;
2122 dotlockUnlock(id, NO_LOCK);
2123 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002124 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002125 }
drh734c9862008-11-28 15:37:20 +00002126 return rc;
2127}
2128/****************** End of the dot-file lock implementation *******************
2129******************************************************************************/
2130
2131/******************************************************************************
2132************************** Begin flock Locking ********************************
2133**
2134** Use the flock() system call to do file locking.
2135**
drh6b9d6dd2008-12-03 19:34:47 +00002136** flock() locking is like dot-file locking in that the various
2137** fine-grain locking levels supported by SQLite are collapsed into
2138** a single exclusive lock. In other words, SHARED, RESERVED, and
2139** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2140** still works when you do this, but concurrency is reduced since
2141** only a single process can be reading the database at a time.
2142**
drh734c9862008-11-28 15:37:20 +00002143** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2144** compiling for VXWORKS.
2145*/
2146#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002147
drh6b9d6dd2008-12-03 19:34:47 +00002148/*
drhff812312011-02-23 13:33:46 +00002149** Retry flock() calls that fail with EINTR
2150*/
2151#ifdef EINTR
2152static int robust_flock(int fd, int op){
2153 int rc;
2154 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2155 return rc;
2156}
2157#else
drh5c819272011-02-23 14:00:12 +00002158# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002159#endif
2160
2161
2162/*
drh6b9d6dd2008-12-03 19:34:47 +00002163** This routine checks if there is a RESERVED lock held on the specified
2164** file by this or any other process. If such a lock is held, set *pResOut
2165** to a non-zero value otherwise *pResOut is set to zero. The return value
2166** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2167*/
drh734c9862008-11-28 15:37:20 +00002168static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2169 int rc = SQLITE_OK;
2170 int reserved = 0;
2171 unixFile *pFile = (unixFile*)id;
2172
2173 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2174
2175 assert( pFile );
2176
2177 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002178 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002179 reserved = 1;
2180 }
2181
2182 /* Otherwise see if some other process holds it. */
2183 if( !reserved ){
2184 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002185 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002186 if( !lrc ){
2187 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002188 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002189 if ( lrc ) {
2190 int tErrno = errno;
2191 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002192 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002193 if( IS_LOCK_ERROR(lrc) ){
2194 pFile->lastErrno = tErrno;
2195 rc = lrc;
2196 }
2197 }
2198 } else {
2199 int tErrno = errno;
2200 reserved = 1;
2201 /* someone else might have it reserved */
2202 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2203 if( IS_LOCK_ERROR(lrc) ){
2204 pFile->lastErrno = tErrno;
2205 rc = lrc;
2206 }
2207 }
2208 }
drh308c2a52010-05-14 11:30:18 +00002209 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002210
2211#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2212 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2213 rc = SQLITE_OK;
2214 reserved=1;
2215 }
2216#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2217 *pResOut = reserved;
2218 return rc;
2219}
2220
drh6b9d6dd2008-12-03 19:34:47 +00002221/*
drh308c2a52010-05-14 11:30:18 +00002222** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002223** of the following:
2224**
2225** (1) SHARED_LOCK
2226** (2) RESERVED_LOCK
2227** (3) PENDING_LOCK
2228** (4) EXCLUSIVE_LOCK
2229**
2230** Sometimes when requesting one lock state, additional lock states
2231** are inserted in between. The locking might fail on one of the later
2232** transitions leaving the lock state different from what it started but
2233** still short of its goal. The following chart shows the allowed
2234** transitions and the inserted intermediate states:
2235**
2236** UNLOCKED -> SHARED
2237** SHARED -> RESERVED
2238** SHARED -> (PENDING) -> EXCLUSIVE
2239** RESERVED -> (PENDING) -> EXCLUSIVE
2240** PENDING -> EXCLUSIVE
2241**
2242** flock() only really support EXCLUSIVE locks. We track intermediate
2243** lock states in the sqlite3_file structure, but all locks SHARED or
2244** above are really EXCLUSIVE locks and exclude all other processes from
2245** access the file.
2246**
2247** This routine will only increase a lock. Use the sqlite3OsUnlock()
2248** routine to lower a locking level.
2249*/
drh308c2a52010-05-14 11:30:18 +00002250static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002251 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002252 unixFile *pFile = (unixFile*)id;
2253
2254 assert( pFile );
2255
2256 /* if we already have a lock, it is exclusive.
2257 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002258 if (pFile->eFileLock > NO_LOCK) {
2259 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002260 return SQLITE_OK;
2261 }
2262
2263 /* grab an exclusive lock */
2264
drhff812312011-02-23 13:33:46 +00002265 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002266 int tErrno = errno;
2267 /* didn't get, must be busy */
2268 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2269 if( IS_LOCK_ERROR(rc) ){
2270 pFile->lastErrno = tErrno;
2271 }
2272 } else {
2273 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002274 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002275 }
drh308c2a52010-05-14 11:30:18 +00002276 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2277 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002278#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2279 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2280 rc = SQLITE_BUSY;
2281 }
2282#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2283 return rc;
2284}
2285
drh6b9d6dd2008-12-03 19:34:47 +00002286
2287/*
drh308c2a52010-05-14 11:30:18 +00002288** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002289** must be either NO_LOCK or SHARED_LOCK.
2290**
2291** If the locking level of the file descriptor is already at or below
2292** the requested locking level, this routine is a no-op.
2293*/
drh308c2a52010-05-14 11:30:18 +00002294static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002295 unixFile *pFile = (unixFile*)id;
2296
2297 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002298 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2299 pFile->eFileLock, getpid()));
2300 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002301
2302 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002303 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002304 return SQLITE_OK;
2305 }
2306
2307 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002308 if (eFileLock==SHARED_LOCK) {
2309 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002310 return SQLITE_OK;
2311 }
2312
2313 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002314 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002315#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002316 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002317#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002318 return SQLITE_IOERR_UNLOCK;
2319 }else{
drh308c2a52010-05-14 11:30:18 +00002320 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002321 return SQLITE_OK;
2322 }
2323}
2324
2325/*
2326** Close a file.
2327*/
2328static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002329 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002330 if( id ){
2331 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002332 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002333 }
drh5a05be12012-10-09 18:51:44 +00002334 return rc;
drh734c9862008-11-28 15:37:20 +00002335}
2336
2337#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2338
2339/******************* End of the flock lock implementation *********************
2340******************************************************************************/
2341
2342/******************************************************************************
2343************************ Begin Named Semaphore Locking ************************
2344**
2345** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002346**
2347** Semaphore locking is like dot-lock and flock in that it really only
2348** supports EXCLUSIVE locking. Only a single process can read or write
2349** the database file at a time. This reduces potential concurrency, but
2350** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002351*/
2352#if OS_VXWORKS
2353
drh6b9d6dd2008-12-03 19:34:47 +00002354/*
2355** This routine checks if there is a RESERVED lock held on the specified
2356** file by this or any other process. If such a lock is held, set *pResOut
2357** to a non-zero value otherwise *pResOut is set to zero. The return value
2358** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2359*/
drh734c9862008-11-28 15:37:20 +00002360static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2361 int rc = SQLITE_OK;
2362 int reserved = 0;
2363 unixFile *pFile = (unixFile*)id;
2364
2365 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2366
2367 assert( pFile );
2368
2369 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002370 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002371 reserved = 1;
2372 }
2373
2374 /* Otherwise see if some other process holds it. */
2375 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002376 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002377 struct stat statBuf;
2378
2379 if( sem_trywait(pSem)==-1 ){
2380 int tErrno = errno;
2381 if( EAGAIN != tErrno ){
2382 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2383 pFile->lastErrno = tErrno;
2384 } else {
2385 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002386 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002387 }
2388 }else{
2389 /* we could have it if we want it */
2390 sem_post(pSem);
2391 }
2392 }
drh308c2a52010-05-14 11:30:18 +00002393 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002394
2395 *pResOut = reserved;
2396 return rc;
2397}
2398
drh6b9d6dd2008-12-03 19:34:47 +00002399/*
drh308c2a52010-05-14 11:30:18 +00002400** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002401** of the following:
2402**
2403** (1) SHARED_LOCK
2404** (2) RESERVED_LOCK
2405** (3) PENDING_LOCK
2406** (4) EXCLUSIVE_LOCK
2407**
2408** Sometimes when requesting one lock state, additional lock states
2409** are inserted in between. The locking might fail on one of the later
2410** transitions leaving the lock state different from what it started but
2411** still short of its goal. The following chart shows the allowed
2412** transitions and the inserted intermediate states:
2413**
2414** UNLOCKED -> SHARED
2415** SHARED -> RESERVED
2416** SHARED -> (PENDING) -> EXCLUSIVE
2417** RESERVED -> (PENDING) -> EXCLUSIVE
2418** PENDING -> EXCLUSIVE
2419**
2420** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2421** lock states in the sqlite3_file structure, but all locks SHARED or
2422** above are really EXCLUSIVE locks and exclude all other processes from
2423** access the file.
2424**
2425** This routine will only increase a lock. Use the sqlite3OsUnlock()
2426** routine to lower a locking level.
2427*/
drh308c2a52010-05-14 11:30:18 +00002428static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002429 unixFile *pFile = (unixFile*)id;
2430 int fd;
drh8af6c222010-05-14 12:43:01 +00002431 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002432 int rc = SQLITE_OK;
2433
2434 /* if we already have a lock, it is exclusive.
2435 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002436 if (pFile->eFileLock > NO_LOCK) {
2437 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002438 rc = SQLITE_OK;
2439 goto sem_end_lock;
2440 }
2441
2442 /* lock semaphore now but bail out when already locked. */
2443 if( sem_trywait(pSem)==-1 ){
2444 rc = SQLITE_BUSY;
2445 goto sem_end_lock;
2446 }
2447
2448 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002449 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002450
2451 sem_end_lock:
2452 return rc;
2453}
2454
drh6b9d6dd2008-12-03 19:34:47 +00002455/*
drh308c2a52010-05-14 11:30:18 +00002456** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002457** must be either NO_LOCK or SHARED_LOCK.
2458**
2459** If the locking level of the file descriptor is already at or below
2460** the requested locking level, this routine is a no-op.
2461*/
drh308c2a52010-05-14 11:30:18 +00002462static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002463 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002464 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002465
2466 assert( pFile );
2467 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002468 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002469 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002470 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002471
2472 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002473 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002474 return SQLITE_OK;
2475 }
2476
2477 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002478 if (eFileLock==SHARED_LOCK) {
2479 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002480 return SQLITE_OK;
2481 }
2482
2483 /* no, really unlock. */
2484 if ( sem_post(pSem)==-1 ) {
2485 int rc, tErrno = errno;
2486 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2487 if( IS_LOCK_ERROR(rc) ){
2488 pFile->lastErrno = tErrno;
2489 }
2490 return rc;
2491 }
drh308c2a52010-05-14 11:30:18 +00002492 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002493 return SQLITE_OK;
2494}
2495
2496/*
2497 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002498 */
drh734c9862008-11-28 15:37:20 +00002499static int semClose(sqlite3_file *id) {
2500 if( id ){
2501 unixFile *pFile = (unixFile*)id;
2502 semUnlock(id, NO_LOCK);
2503 assert( pFile );
2504 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002505 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002506 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002507 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002508 }
2509 return SQLITE_OK;
2510}
2511
2512#endif /* OS_VXWORKS */
2513/*
2514** Named semaphore locking is only available on VxWorks.
2515**
2516*************** End of the named semaphore lock implementation ****************
2517******************************************************************************/
2518
2519
2520/******************************************************************************
2521*************************** Begin AFP Locking *********************************
2522**
2523** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2524** on Apple Macintosh computers - both OS9 and OSX.
2525**
2526** Third-party implementations of AFP are available. But this code here
2527** only works on OSX.
2528*/
2529
drhd2cb50b2009-01-09 21:41:17 +00002530#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002531/*
2532** The afpLockingContext structure contains all afp lock specific state
2533*/
drhbfe66312006-10-03 17:40:40 +00002534typedef struct afpLockingContext afpLockingContext;
2535struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002536 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002537 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002538};
2539
2540struct ByteRangeLockPB2
2541{
2542 unsigned long long offset; /* offset to first byte to lock */
2543 unsigned long long length; /* nbr of bytes to lock */
2544 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2545 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2546 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2547 int fd; /* file desc to assoc this lock with */
2548};
2549
drhfd131da2007-08-07 17:13:03 +00002550#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002551
drh6b9d6dd2008-12-03 19:34:47 +00002552/*
2553** This is a utility for setting or clearing a bit-range lock on an
2554** AFP filesystem.
2555**
2556** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2557*/
2558static int afpSetLock(
2559 const char *path, /* Name of the file to be locked or unlocked */
2560 unixFile *pFile, /* Open file descriptor on path */
2561 unsigned long long offset, /* First byte to be locked */
2562 unsigned long long length, /* Number of bytes to lock */
2563 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002564){
drh6b9d6dd2008-12-03 19:34:47 +00002565 struct ByteRangeLockPB2 pb;
2566 int err;
drhbfe66312006-10-03 17:40:40 +00002567
2568 pb.unLockFlag = setLockFlag ? 0 : 1;
2569 pb.startEndFlag = 0;
2570 pb.offset = offset;
2571 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002572 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002573
drh308c2a52010-05-14 11:30:18 +00002574 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002575 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002576 offset, length));
drhbfe66312006-10-03 17:40:40 +00002577 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2578 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002579 int rc;
2580 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002581 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2582 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002583#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2584 rc = SQLITE_BUSY;
2585#else
drh734c9862008-11-28 15:37:20 +00002586 rc = sqliteErrorFromPosixError(tErrno,
2587 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002588#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002589 if( IS_LOCK_ERROR(rc) ){
2590 pFile->lastErrno = tErrno;
2591 }
2592 return rc;
drhbfe66312006-10-03 17:40:40 +00002593 } else {
aswift5b1a2562008-08-22 00:22:35 +00002594 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002595 }
2596}
2597
drh6b9d6dd2008-12-03 19:34:47 +00002598/*
2599** This routine checks if there is a RESERVED lock held on the specified
2600** file by this or any other process. If such a lock is held, set *pResOut
2601** to a non-zero value otherwise *pResOut is set to zero. The return value
2602** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2603*/
danielk1977e339d652008-06-28 11:23:00 +00002604static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002605 int rc = SQLITE_OK;
2606 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002607 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002608 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002609
aswift5b1a2562008-08-22 00:22:35 +00002610 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2611
2612 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002613 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002614 if( context->reserved ){
2615 *pResOut = 1;
2616 return SQLITE_OK;
2617 }
drh8af6c222010-05-14 12:43:01 +00002618 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002619
2620 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002621 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002622 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002623 }
2624
2625 /* Otherwise see if some other process holds it.
2626 */
aswift5b1a2562008-08-22 00:22:35 +00002627 if( !reserved ){
2628 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002629 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002630 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002631 /* if we succeeded in taking the reserved lock, unlock it to restore
2632 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002633 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002634 } else {
2635 /* if we failed to get the lock then someone else must have it */
2636 reserved = 1;
2637 }
2638 if( IS_LOCK_ERROR(lrc) ){
2639 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002640 }
2641 }
drhbfe66312006-10-03 17:40:40 +00002642
drh7ed97b92010-01-20 13:07:21 +00002643 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002644 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002645
2646 *pResOut = reserved;
2647 return rc;
drhbfe66312006-10-03 17:40:40 +00002648}
2649
drh6b9d6dd2008-12-03 19:34:47 +00002650/*
drh308c2a52010-05-14 11:30:18 +00002651** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002652** of the following:
2653**
2654** (1) SHARED_LOCK
2655** (2) RESERVED_LOCK
2656** (3) PENDING_LOCK
2657** (4) EXCLUSIVE_LOCK
2658**
2659** Sometimes when requesting one lock state, additional lock states
2660** are inserted in between. The locking might fail on one of the later
2661** transitions leaving the lock state different from what it started but
2662** still short of its goal. The following chart shows the allowed
2663** transitions and the inserted intermediate states:
2664**
2665** UNLOCKED -> SHARED
2666** SHARED -> RESERVED
2667** SHARED -> (PENDING) -> EXCLUSIVE
2668** RESERVED -> (PENDING) -> EXCLUSIVE
2669** PENDING -> EXCLUSIVE
2670**
2671** This routine will only increase a lock. Use the sqlite3OsUnlock()
2672** routine to lower a locking level.
2673*/
drh308c2a52010-05-14 11:30:18 +00002674static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002675 int rc = SQLITE_OK;
2676 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002677 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002678 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002679
2680 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002681 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2682 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002683 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002684
drhbfe66312006-10-03 17:40:40 +00002685 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002686 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002687 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002688 */
drh308c2a52010-05-14 11:30:18 +00002689 if( pFile->eFileLock>=eFileLock ){
2690 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2691 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002692 return SQLITE_OK;
2693 }
2694
2695 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002696 ** (1) We never move from unlocked to anything higher than shared lock.
2697 ** (2) SQLite never explicitly requests a pendig lock.
2698 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002699 */
drh308c2a52010-05-14 11:30:18 +00002700 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2701 assert( eFileLock!=PENDING_LOCK );
2702 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002703
drh8af6c222010-05-14 12:43:01 +00002704 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002705 */
drh6c7d5c52008-11-21 20:32:33 +00002706 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002707 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002708
2709 /* If some thread using this PID has a lock via a different unixFile*
2710 ** handle that precludes the requested lock, return BUSY.
2711 */
drh8af6c222010-05-14 12:43:01 +00002712 if( (pFile->eFileLock!=pInode->eFileLock &&
2713 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002714 ){
2715 rc = SQLITE_BUSY;
2716 goto afp_end_lock;
2717 }
2718
2719 /* If a SHARED lock is requested, and some thread using this PID already
2720 ** has a SHARED or RESERVED lock, then increment reference counts and
2721 ** return SQLITE_OK.
2722 */
drh308c2a52010-05-14 11:30:18 +00002723 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002724 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002725 assert( eFileLock==SHARED_LOCK );
2726 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002727 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002728 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002729 pInode->nShared++;
2730 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002731 goto afp_end_lock;
2732 }
drhbfe66312006-10-03 17:40:40 +00002733
2734 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002735 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2736 ** be released.
2737 */
drh308c2a52010-05-14 11:30:18 +00002738 if( eFileLock==SHARED_LOCK
2739 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002740 ){
2741 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002742 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002743 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002744 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002745 goto afp_end_lock;
2746 }
2747 }
2748
2749 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002750 ** operating system calls for the specified lock.
2751 */
drh308c2a52010-05-14 11:30:18 +00002752 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002753 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002754 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002755
drh8af6c222010-05-14 12:43:01 +00002756 assert( pInode->nShared==0 );
2757 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002758
2759 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002760 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002761 /* note that the quality of the randomness doesn't matter that much */
2762 lk = random();
drh8af6c222010-05-14 12:43:01 +00002763 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002764 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002765 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002766 if( IS_LOCK_ERROR(lrc1) ){
2767 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002768 }
aswift5b1a2562008-08-22 00:22:35 +00002769 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002770 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002771
aswift5b1a2562008-08-22 00:22:35 +00002772 if( IS_LOCK_ERROR(lrc1) ) {
2773 pFile->lastErrno = lrc1Errno;
2774 rc = lrc1;
2775 goto afp_end_lock;
2776 } else if( IS_LOCK_ERROR(lrc2) ){
2777 rc = lrc2;
2778 goto afp_end_lock;
2779 } else if( lrc1 != SQLITE_OK ) {
2780 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002781 } else {
drh308c2a52010-05-14 11:30:18 +00002782 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002783 pInode->nLock++;
2784 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002785 }
drh8af6c222010-05-14 12:43:01 +00002786 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002787 /* We are trying for an exclusive lock but another thread in this
2788 ** same process is still holding a shared lock. */
2789 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002790 }else{
2791 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2792 ** assumed that there is a SHARED or greater lock on the file
2793 ** already.
2794 */
2795 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002796 assert( 0!=pFile->eFileLock );
2797 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002798 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002799 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002800 if( !failed ){
2801 context->reserved = 1;
2802 }
drhbfe66312006-10-03 17:40:40 +00002803 }
drh308c2a52010-05-14 11:30:18 +00002804 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002805 /* Acquire an EXCLUSIVE lock */
2806
2807 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002808 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002809 */
drh6b9d6dd2008-12-03 19:34:47 +00002810 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002811 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002812 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002813 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002814 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002815 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002816 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002817 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002818 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2819 ** a critical I/O error
2820 */
2821 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2822 SQLITE_IOERR_LOCK;
2823 goto afp_end_lock;
2824 }
2825 }else{
aswift5b1a2562008-08-22 00:22:35 +00002826 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002827 }
2828 }
aswift5b1a2562008-08-22 00:22:35 +00002829 if( failed ){
2830 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002831 }
2832 }
2833
2834 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002835 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002836 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002837 }else if( eFileLock==EXCLUSIVE_LOCK ){
2838 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002839 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002840 }
2841
2842afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002843 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002844 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2845 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002846 return rc;
2847}
2848
2849/*
drh308c2a52010-05-14 11:30:18 +00002850** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002851** must be either NO_LOCK or SHARED_LOCK.
2852**
2853** If the locking level of the file descriptor is already at or below
2854** the requested locking level, this routine is a no-op.
2855*/
drh308c2a52010-05-14 11:30:18 +00002856static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002857 int rc = SQLITE_OK;
2858 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002859 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002860 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2861 int skipShared = 0;
2862#ifdef SQLITE_TEST
2863 int h = pFile->h;
2864#endif
drhbfe66312006-10-03 17:40:40 +00002865
2866 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002867 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002868 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002869 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002870
drh308c2a52010-05-14 11:30:18 +00002871 assert( eFileLock<=SHARED_LOCK );
2872 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002873 return SQLITE_OK;
2874 }
drh6c7d5c52008-11-21 20:32:33 +00002875 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002876 pInode = pFile->pInode;
2877 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002878 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002879 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002880 SimulateIOErrorBenign(1);
2881 SimulateIOError( h=(-1) )
2882 SimulateIOErrorBenign(0);
2883
drhd3d8c042012-05-29 17:02:40 +00002884#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002885 /* When reducing a lock such that other processes can start
2886 ** reading the database file again, make sure that the
2887 ** transaction counter was updated if any part of the database
2888 ** file changed. If the transaction counter is not updated,
2889 ** other connections to the same file might not realize that
2890 ** the file has changed and hence might not know to flush their
2891 ** cache. The use of a stale cache can lead to database corruption.
2892 */
2893 assert( pFile->inNormalWrite==0
2894 || pFile->dbUpdate==0
2895 || pFile->transCntrChng==1 );
2896 pFile->inNormalWrite = 0;
2897#endif
aswiftaebf4132008-11-21 00:10:35 +00002898
drh308c2a52010-05-14 11:30:18 +00002899 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002900 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002901 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002902 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002903 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002904 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2905 } else {
2906 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002907 }
2908 }
drh308c2a52010-05-14 11:30:18 +00002909 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002910 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002911 }
drh308c2a52010-05-14 11:30:18 +00002912 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002913 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2914 if( !rc ){
2915 context->reserved = 0;
2916 }
aswiftaebf4132008-11-21 00:10:35 +00002917 }
drh8af6c222010-05-14 12:43:01 +00002918 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2919 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002920 }
aswiftaebf4132008-11-21 00:10:35 +00002921 }
drh308c2a52010-05-14 11:30:18 +00002922 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002923
drh7ed97b92010-01-20 13:07:21 +00002924 /* Decrement the shared lock counter. Release the lock using an
2925 ** OS call only when all threads in this same process have released
2926 ** the lock.
2927 */
drh8af6c222010-05-14 12:43:01 +00002928 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2929 pInode->nShared--;
2930 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002931 SimulateIOErrorBenign(1);
2932 SimulateIOError( h=(-1) )
2933 SimulateIOErrorBenign(0);
2934 if( !skipShared ){
2935 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2936 }
2937 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002938 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002939 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002940 }
2941 }
2942 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002943 pInode->nLock--;
2944 assert( pInode->nLock>=0 );
2945 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002946 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002947 }
2948 }
drhbfe66312006-10-03 17:40:40 +00002949 }
drh7ed97b92010-01-20 13:07:21 +00002950
drh6c7d5c52008-11-21 20:32:33 +00002951 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002952 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002953 return rc;
2954}
2955
2956/*
drh339eb0b2008-03-07 15:34:11 +00002957** Close a file & cleanup AFP specific locking context
2958*/
danielk1977e339d652008-06-28 11:23:00 +00002959static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002960 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002961 if( id ){
2962 unixFile *pFile = (unixFile*)id;
2963 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002964 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002965 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002966 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002967 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002968 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002969 ** the last lock is cleared.
2970 */
dan08da86a2009-08-21 17:18:03 +00002971 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002972 }
danb0ac3e32010-06-16 10:55:42 +00002973 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002974 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002975 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002976 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002977 }
drh7ed97b92010-01-20 13:07:21 +00002978 return rc;
drhbfe66312006-10-03 17:40:40 +00002979}
2980
drhd2cb50b2009-01-09 21:41:17 +00002981#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002982/*
2983** The code above is the AFP lock implementation. The code is specific
2984** to MacOSX and does not work on other unix platforms. No alternative
2985** is available. If you don't compile for a mac, then the "unix-afp"
2986** VFS is not available.
2987**
2988********************* End of the AFP lock implementation **********************
2989******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002990
drh7ed97b92010-01-20 13:07:21 +00002991/******************************************************************************
2992*************************** Begin NFS Locking ********************************/
2993
2994#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2995/*
drh308c2a52010-05-14 11:30:18 +00002996 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002997 ** must be either NO_LOCK or SHARED_LOCK.
2998 **
2999 ** If the locking level of the file descriptor is already at or below
3000 ** the requested locking level, this routine is a no-op.
3001 */
drh308c2a52010-05-14 11:30:18 +00003002static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003003 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003004}
3005
3006#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3007/*
3008** The code above is the NFS lock implementation. The code is specific
3009** to MacOSX and does not work on other unix platforms. No alternative
3010** is available.
3011**
3012********************* End of the NFS lock implementation **********************
3013******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003014
3015/******************************************************************************
3016**************** Non-locking sqlite3_file methods *****************************
3017**
3018** The next division contains implementations for all methods of the
3019** sqlite3_file object other than the locking methods. The locking
3020** methods were defined in divisions above (one locking method per
3021** division). Those methods that are common to all locking modes
3022** are gather together into this division.
3023*/
drhbfe66312006-10-03 17:40:40 +00003024
3025/*
drh734c9862008-11-28 15:37:20 +00003026** Seek to the offset passed as the second argument, then read cnt
3027** bytes into pBuf. Return the number of bytes actually read.
3028**
3029** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3030** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3031** one system to another. Since SQLite does not define USE_PREAD
3032** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3033** See tickets #2741 and #2681.
3034**
3035** To avoid stomping the errno value on a failed read the lastErrno value
3036** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003037*/
drh734c9862008-11-28 15:37:20 +00003038static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3039 int got;
drh58024642011-11-07 18:16:00 +00003040 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003041#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003042 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003043#endif
drh734c9862008-11-28 15:37:20 +00003044 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003045 assert( cnt==(cnt&0x1ffff) );
3046 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003047 do{
drh734c9862008-11-28 15:37:20 +00003048#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003049 got = osPread(id->h, pBuf, cnt, offset);
3050 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003051#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003052 got = osPread64(id->h, pBuf, cnt, offset);
3053 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003054#else
drh58024642011-11-07 18:16:00 +00003055 newOffset = lseek(id->h, offset, SEEK_SET);
3056 SimulateIOError( newOffset-- );
3057 if( newOffset!=offset ){
3058 if( newOffset == -1 ){
3059 ((unixFile*)id)->lastErrno = errno;
3060 }else{
drhf2f105d2012-08-20 15:53:54 +00003061 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003062 }
3063 return -1;
drh734c9862008-11-28 15:37:20 +00003064 }
drh58024642011-11-07 18:16:00 +00003065 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003066#endif
drh58024642011-11-07 18:16:00 +00003067 if( got==cnt ) break;
3068 if( got<0 ){
3069 if( errno==EINTR ){ got = 1; continue; }
3070 prior = 0;
3071 ((unixFile*)id)->lastErrno = errno;
3072 break;
3073 }else if( got>0 ){
3074 cnt -= got;
3075 offset += got;
3076 prior += got;
3077 pBuf = (void*)(got + (char*)pBuf);
3078 }
3079 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003080 TIMER_END;
drh58024642011-11-07 18:16:00 +00003081 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3082 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3083 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003084}
3085
3086/*
drh734c9862008-11-28 15:37:20 +00003087** Read data from a file into a buffer. Return SQLITE_OK if all
3088** bytes were read successfully and SQLITE_IOERR if anything goes
3089** wrong.
drh339eb0b2008-03-07 15:34:11 +00003090*/
drh734c9862008-11-28 15:37:20 +00003091static int unixRead(
3092 sqlite3_file *id,
3093 void *pBuf,
3094 int amt,
3095 sqlite3_int64 offset
3096){
dan08da86a2009-08-21 17:18:03 +00003097 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003098 int got;
3099 assert( id );
drh08c6d442009-02-09 17:34:07 +00003100
dan08da86a2009-08-21 17:18:03 +00003101 /* If this is a database file (not a journal, master-journal or temp
3102 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003103#if 0
dane946c392009-08-22 11:39:46 +00003104 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003105 || offset>=PENDING_BYTE+512
3106 || offset+amt<=PENDING_BYTE
3107 );
dan7c246102010-04-12 19:00:29 +00003108#endif
drh08c6d442009-02-09 17:34:07 +00003109
danf23da962013-03-23 21:00:41 +00003110 /* Deal with as much of this write request as possible by transfering
3111 ** data to the memory mapping using memcpy(). */
3112 if( offset<pFile->mmapSize ){
3113 if( offset+amt <= pFile->mmapSize ){
3114 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3115 return SQLITE_OK;
3116 }else{
3117 int nCopy = pFile->mmapSize - offset;
3118 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3119 pBuf = &((u8 *)pBuf)[nCopy];
3120 amt -= nCopy;
3121 offset += nCopy;
3122 }
3123 }
3124
dan08da86a2009-08-21 17:18:03 +00003125 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003126 if( got==amt ){
3127 return SQLITE_OK;
3128 }else if( got<0 ){
3129 /* lastErrno set by seekAndRead */
3130 return SQLITE_IOERR_READ;
3131 }else{
dan08da86a2009-08-21 17:18:03 +00003132 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003133 /* Unread parts of the buffer must be zero-filled */
3134 memset(&((char*)pBuf)[got], 0, amt-got);
3135 return SQLITE_IOERR_SHORT_READ;
3136 }
3137}
3138
3139/*
3140** Seek to the offset in id->offset then read cnt bytes into pBuf.
3141** Return the number of bytes actually read. Update the offset.
3142**
3143** To avoid stomping the errno value on a failed write the lastErrno value
3144** is set before returning.
3145*/
3146static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3147 int got;
drh7ed97b92010-01-20 13:07:21 +00003148#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003149 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003150#endif
drhc1fd2cf2012-10-01 12:16:26 +00003151 assert( cnt==(cnt&0x1ffff) );
3152 cnt &= 0x1ffff;
drh734c9862008-11-28 15:37:20 +00003153 TIMER_START;
3154#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003155 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003156#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003157 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003158#else
drhbd1e50c2011-08-19 14:54:12 +00003159 do{
3160 newOffset = lseek(id->h, offset, SEEK_SET);
3161 SimulateIOError( newOffset-- );
3162 if( newOffset!=offset ){
3163 if( newOffset == -1 ){
3164 ((unixFile*)id)->lastErrno = errno;
3165 }else{
drhf2f105d2012-08-20 15:53:54 +00003166 ((unixFile*)id)->lastErrno = 0;
drhbd1e50c2011-08-19 14:54:12 +00003167 }
3168 return -1;
drh734c9862008-11-28 15:37:20 +00003169 }
drhbd1e50c2011-08-19 14:54:12 +00003170 got = osWrite(id->h, pBuf, cnt);
3171 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003172#endif
3173 TIMER_END;
3174 if( got<0 ){
3175 ((unixFile*)id)->lastErrno = errno;
3176 }
3177
drh308c2a52010-05-14 11:30:18 +00003178 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003179 return got;
3180}
3181
3182
3183/*
3184** Write data from a buffer into a file. Return SQLITE_OK on success
3185** or some other error code on failure.
3186*/
3187static int unixWrite(
3188 sqlite3_file *id,
3189 const void *pBuf,
3190 int amt,
3191 sqlite3_int64 offset
3192){
dan08da86a2009-08-21 17:18:03 +00003193 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003194 int wrote = 0;
3195 assert( id );
3196 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003197
dan08da86a2009-08-21 17:18:03 +00003198 /* If this is a database file (not a journal, master-journal or temp
3199 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003200#if 0
dane946c392009-08-22 11:39:46 +00003201 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003202 || offset>=PENDING_BYTE+512
3203 || offset+amt<=PENDING_BYTE
3204 );
dan7c246102010-04-12 19:00:29 +00003205#endif
drh08c6d442009-02-09 17:34:07 +00003206
drhd3d8c042012-05-29 17:02:40 +00003207#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003208 /* If we are doing a normal write to a database file (as opposed to
3209 ** doing a hot-journal rollback or a write to some file other than a
3210 ** normal database file) then record the fact that the database
3211 ** has changed. If the transaction counter is modified, record that
3212 ** fact too.
3213 */
dan08da86a2009-08-21 17:18:03 +00003214 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003215 pFile->dbUpdate = 1; /* The database has been modified */
3216 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003217 int rc;
drh8f941bc2009-01-14 23:03:40 +00003218 char oldCntr[4];
3219 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003220 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003221 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003222 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003223 pFile->transCntrChng = 1; /* The transaction counter has changed */
3224 }
3225 }
3226 }
3227#endif
3228
danf23da962013-03-23 21:00:41 +00003229 /* Deal with as much of this write request as possible by transfering
3230 ** data from the memory mapping using memcpy(). */
3231 if( offset<pFile->mmapSize ){
3232 if( offset+amt <= pFile->mmapSize ){
3233 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3234 return SQLITE_OK;
3235 }else{
3236 int nCopy = pFile->mmapSize - offset;
3237 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3238 pBuf = &((u8 *)pBuf)[nCopy];
3239 amt -= nCopy;
3240 offset += nCopy;
3241 }
3242 }
3243
dan08da86a2009-08-21 17:18:03 +00003244 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003245 amt -= wrote;
3246 offset += wrote;
3247 pBuf = &((char*)pBuf)[wrote];
3248 }
3249 SimulateIOError(( wrote=(-1), amt=1 ));
3250 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003251
drh734c9862008-11-28 15:37:20 +00003252 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003253 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003254 /* lastErrno set by seekAndWrite */
3255 return SQLITE_IOERR_WRITE;
3256 }else{
dan08da86a2009-08-21 17:18:03 +00003257 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003258 return SQLITE_FULL;
3259 }
3260 }
dan6e09d692010-07-27 18:34:15 +00003261
drh734c9862008-11-28 15:37:20 +00003262 return SQLITE_OK;
3263}
3264
3265#ifdef SQLITE_TEST
3266/*
3267** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003268** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003269*/
3270int sqlite3_sync_count = 0;
3271int sqlite3_fullsync_count = 0;
3272#endif
3273
3274/*
drh89240432009-03-25 01:06:01 +00003275** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003276** Others do no. To be safe, we will stick with the (slightly slower)
3277** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003278** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003279*/
drh20f8e132011-08-31 21:01:55 +00003280#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003281# define fdatasync fsync
3282#endif
3283
3284/*
3285** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3286** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3287** only available on Mac OS X. But that could change.
3288*/
3289#ifdef F_FULLFSYNC
3290# define HAVE_FULLFSYNC 1
3291#else
3292# define HAVE_FULLFSYNC 0
3293#endif
3294
3295
3296/*
3297** The fsync() system call does not work as advertised on many
3298** unix systems. The following procedure is an attempt to make
3299** it work better.
3300**
3301** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3302** for testing when we want to run through the test suite quickly.
3303** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3304** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3305** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003306**
3307** SQLite sets the dataOnly flag if the size of the file is unchanged.
3308** The idea behind dataOnly is that it should only write the file content
3309** to disk, not the inode. We only set dataOnly if the file size is
3310** unchanged since the file size is part of the inode. However,
3311** Ted Ts'o tells us that fdatasync() will also write the inode if the
3312** file size has changed. The only real difference between fdatasync()
3313** and fsync(), Ted tells us, is that fdatasync() will not flush the
3314** inode if the mtime or owner or other inode attributes have changed.
3315** We only care about the file size, not the other file attributes, so
3316** as far as SQLite is concerned, an fdatasync() is always adequate.
3317** So, we always use fdatasync() if it is available, regardless of
3318** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003319*/
3320static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003321 int rc;
drh734c9862008-11-28 15:37:20 +00003322
3323 /* The following "ifdef/elif/else/" block has the same structure as
3324 ** the one below. It is replicated here solely to avoid cluttering
3325 ** up the real code with the UNUSED_PARAMETER() macros.
3326 */
3327#ifdef SQLITE_NO_SYNC
3328 UNUSED_PARAMETER(fd);
3329 UNUSED_PARAMETER(fullSync);
3330 UNUSED_PARAMETER(dataOnly);
3331#elif HAVE_FULLFSYNC
3332 UNUSED_PARAMETER(dataOnly);
3333#else
3334 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003335 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003336#endif
3337
3338 /* Record the number of times that we do a normal fsync() and
3339 ** FULLSYNC. This is used during testing to verify that this procedure
3340 ** gets called with the correct arguments.
3341 */
3342#ifdef SQLITE_TEST
3343 if( fullSync ) sqlite3_fullsync_count++;
3344 sqlite3_sync_count++;
3345#endif
3346
3347 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3348 ** no-op
3349 */
3350#ifdef SQLITE_NO_SYNC
3351 rc = SQLITE_OK;
3352#elif HAVE_FULLFSYNC
3353 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003354 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003355 }else{
3356 rc = 1;
3357 }
3358 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003359 ** It shouldn't be possible for fullfsync to fail on the local
3360 ** file system (on OSX), so failure indicates that FULLFSYNC
3361 ** isn't supported for this file system. So, attempt an fsync
3362 ** and (for now) ignore the overhead of a superfluous fcntl call.
3363 ** It'd be better to detect fullfsync support once and avoid
3364 ** the fcntl call every time sync is called.
3365 */
drh734c9862008-11-28 15:37:20 +00003366 if( rc ) rc = fsync(fd);
3367
drh7ed97b92010-01-20 13:07:21 +00003368#elif defined(__APPLE__)
3369 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3370 ** so currently we default to the macro that redefines fdatasync to fsync
3371 */
3372 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003373#else
drh0b647ff2009-03-21 14:41:04 +00003374 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003375#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003376 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003377 rc = fsync(fd);
3378 }
drh0b647ff2009-03-21 14:41:04 +00003379#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003380#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3381
3382 if( OS_VXWORKS && rc!= -1 ){
3383 rc = 0;
3384 }
chw97185482008-11-17 08:05:31 +00003385 return rc;
drhbfe66312006-10-03 17:40:40 +00003386}
3387
drh734c9862008-11-28 15:37:20 +00003388/*
drh0059eae2011-08-08 23:48:40 +00003389** Open a file descriptor to the directory containing file zFilename.
3390** If successful, *pFd is set to the opened file descriptor and
3391** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3392** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3393** value.
3394**
drh90315a22011-08-10 01:52:12 +00003395** The directory file descriptor is used for only one thing - to
3396** fsync() a directory to make sure file creation and deletion events
3397** are flushed to disk. Such fsyncs are not needed on newer
3398** journaling filesystems, but are required on older filesystems.
3399**
3400** This routine can be overridden using the xSetSysCall interface.
3401** The ability to override this routine was added in support of the
3402** chromium sandbox. Opening a directory is a security risk (we are
3403** told) so making it overrideable allows the chromium sandbox to
3404** replace this routine with a harmless no-op. To make this routine
3405** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3406** *pFd set to a negative number.
3407**
drh0059eae2011-08-08 23:48:40 +00003408** If SQLITE_OK is returned, the caller is responsible for closing
3409** the file descriptor *pFd using close().
3410*/
3411static int openDirectory(const char *zFilename, int *pFd){
3412 int ii;
3413 int fd = -1;
3414 char zDirname[MAX_PATHNAME+1];
3415
3416 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3417 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3418 if( ii>0 ){
3419 zDirname[ii] = '\0';
3420 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3421 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003422 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3423 }
3424 }
3425 *pFd = fd;
3426 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3427}
3428
3429/*
drh734c9862008-11-28 15:37:20 +00003430** Make sure all writes to a particular file are committed to disk.
3431**
3432** If dataOnly==0 then both the file itself and its metadata (file
3433** size, access time, etc) are synced. If dataOnly!=0 then only the
3434** file data is synced.
3435**
3436** Under Unix, also make sure that the directory entry for the file
3437** has been created by fsync-ing the directory that contains the file.
3438** If we do not do this and we encounter a power failure, the directory
3439** entry for the journal might not exist after we reboot. The next
3440** SQLite to access the file will not know that the journal exists (because
3441** the directory entry for the journal was never created) and the transaction
3442** will not roll back - possibly leading to database corruption.
3443*/
3444static int unixSync(sqlite3_file *id, int flags){
3445 int rc;
3446 unixFile *pFile = (unixFile*)id;
3447
3448 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3449 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3450
3451 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3452 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3453 || (flags&0x0F)==SQLITE_SYNC_FULL
3454 );
3455
3456 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3457 ** line is to test that doing so does not cause any problems.
3458 */
3459 SimulateDiskfullError( return SQLITE_FULL );
3460
3461 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003462 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003463 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3464 SimulateIOError( rc=1 );
3465 if( rc ){
3466 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003467 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003468 }
drh0059eae2011-08-08 23:48:40 +00003469
3470 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003471 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003472 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003473 */
3474 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3475 int dirfd;
3476 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003477 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003478 rc = osOpenDirectory(pFile->zPath, &dirfd);
3479 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003480 full_fsync(dirfd, 0, 0);
3481 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003482 }else if( rc==SQLITE_CANTOPEN ){
3483 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003484 }
drh0059eae2011-08-08 23:48:40 +00003485 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003486 }
3487 return rc;
3488}
3489
3490/*
3491** Truncate an open file to a specified size
3492*/
3493static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003494 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003495 int rc;
dan6e09d692010-07-27 18:34:15 +00003496 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003497 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003498
3499 /* If the user has configured a chunk-size for this file, truncate the
3500 ** file so that it consists of an integer number of chunks (i.e. the
3501 ** actual file size after the operation may be larger than the requested
3502 ** size).
3503 */
drhb8af4b72012-04-05 20:04:39 +00003504 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003505 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3506 }
3507
drhff812312011-02-23 13:33:46 +00003508 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003509 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003510 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003511 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003512 }else{
drhd3d8c042012-05-29 17:02:40 +00003513#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003514 /* If we are doing a normal write to a database file (as opposed to
3515 ** doing a hot-journal rollback or a write to some file other than a
3516 ** normal database file) and we truncate the file to zero length,
3517 ** that effectively updates the change counter. This might happen
3518 ** when restoring a database using the backup API from a zero-length
3519 ** source.
3520 */
dan6e09d692010-07-27 18:34:15 +00003521 if( pFile->inNormalWrite && nByte==0 ){
3522 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003523 }
danf23da962013-03-23 21:00:41 +00003524#endif
danc0003312013-03-22 17:46:11 +00003525
3526 /* If the file was just truncated to a size smaller than the currently
3527 ** mapped region, reduce the effective mapping size as well. SQLite will
3528 ** use read() and write() to access data beyond this point from now on.
3529 */
3530 if( nByte<pFile->mmapSize ){
3531 pFile->mmapSize = nByte;
3532 }
drh3313b142009-11-06 04:13:18 +00003533
drh734c9862008-11-28 15:37:20 +00003534 return SQLITE_OK;
3535 }
3536}
3537
3538/*
3539** Determine the current size of a file in bytes
3540*/
3541static int unixFileSize(sqlite3_file *id, i64 *pSize){
3542 int rc;
3543 struct stat buf;
3544 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003545 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003546 SimulateIOError( rc=1 );
3547 if( rc!=0 ){
3548 ((unixFile*)id)->lastErrno = errno;
3549 return SQLITE_IOERR_FSTAT;
3550 }
3551 *pSize = buf.st_size;
3552
drh8af6c222010-05-14 12:43:01 +00003553 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003554 ** writes a single byte into that file in order to work around a bug
3555 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3556 ** layers, we need to report this file size as zero even though it is
3557 ** really 1. Ticket #3260.
3558 */
3559 if( *pSize==1 ) *pSize = 0;
3560
3561
3562 return SQLITE_OK;
3563}
3564
drhd2cb50b2009-01-09 21:41:17 +00003565#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003566/*
3567** Handler for proxy-locking file-control verbs. Defined below in the
3568** proxying locking division.
3569*/
3570static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003571#endif
drh715ff302008-12-03 22:32:44 +00003572
dan502019c2010-07-28 14:26:17 +00003573/*
3574** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003575** file-control operation. Enlarge the database to nBytes in size
3576** (rounded up to the next chunk-size). If the database is already
3577** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003578*/
3579static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003580 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003581 i64 nSize; /* Required file size */
3582 struct stat buf; /* Used to hold return values of fstat() */
3583
drh99ab3b12011-03-02 15:09:07 +00003584 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003585
3586 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3587 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003588
dan502019c2010-07-28 14:26:17 +00003589#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003590 /* The code below is handling the return value of osFallocate()
3591 ** correctly. posix_fallocate() is defined to "returns zero on success,
3592 ** or an error number on failure". See the manpage for details. */
3593 int err;
drhff812312011-02-23 13:33:46 +00003594 do{
dan661d71a2011-03-30 19:08:03 +00003595 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3596 }while( err==EINTR );
3597 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003598#else
3599 /* If the OS does not have posix_fallocate(), fake it. First use
3600 ** ftruncate() to set the file size, then write a single byte to
3601 ** the last byte in each block within the extended region. This
3602 ** is the same technique used by glibc to implement posix_fallocate()
3603 ** on systems that do not have a real fallocate() system call.
3604 */
3605 int nBlk = buf.st_blksize; /* File-system block size */
3606 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003607
drhff812312011-02-23 13:33:46 +00003608 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003609 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003610 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003611 }
3612 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003613 while( iWrite<nSize ){
3614 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3615 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003616 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003617 }
dan502019c2010-07-28 14:26:17 +00003618#endif
3619 }
3620 }
3621
danf23da962013-03-23 21:00:41 +00003622 if( pFile->mmapLimit>0 ){
3623 int rc;
3624 if( pFile->szChunk<=0 ){
3625 if( robust_ftruncate(pFile->h, nByte) ){
3626 pFile->lastErrno = errno;
3627 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3628 }
3629 }
3630
3631 rc = unixMapfile(pFile, nByte);
3632 return rc;
3633 }
3634
dan502019c2010-07-28 14:26:17 +00003635 return SQLITE_OK;
3636}
danielk1977ad94b582007-08-20 06:44:22 +00003637
danielk1977e3026632004-06-22 11:29:02 +00003638/*
drhf12b3f62011-12-21 14:42:29 +00003639** If *pArg is inititially negative then this is a query. Set *pArg to
3640** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3641**
3642** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3643*/
3644static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3645 if( *pArg<0 ){
3646 *pArg = (pFile->ctrlFlags & mask)!=0;
3647 }else if( (*pArg)==0 ){
3648 pFile->ctrlFlags &= ~mask;
3649 }else{
3650 pFile->ctrlFlags |= mask;
3651 }
3652}
3653
drh696b33e2012-12-06 19:01:42 +00003654/* Forward declaration */
3655static int unixGetTempname(int nBuf, char *zBuf);
3656
drhf12b3f62011-12-21 14:42:29 +00003657/*
drh9e33c2c2007-08-31 18:34:59 +00003658** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003659*/
drhcc6bb3e2007-08-31 16:11:35 +00003660static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003661 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003662 switch( op ){
3663 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003664 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003665 return SQLITE_OK;
3666 }
drh7708e972008-11-29 00:56:52 +00003667 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003668 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003669 return SQLITE_OK;
3670 }
dan6e09d692010-07-27 18:34:15 +00003671 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003672 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003673 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003674 }
drh9ff27ec2010-05-19 19:26:05 +00003675 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003676 int rc;
3677 SimulateIOErrorBenign(1);
3678 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3679 SimulateIOErrorBenign(0);
3680 return rc;
drhf0b190d2011-07-26 16:03:07 +00003681 }
3682 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003683 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3684 return SQLITE_OK;
3685 }
drhcb15f352011-12-23 01:04:17 +00003686 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3687 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003688 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003689 }
drhde60fc22011-12-14 17:53:36 +00003690 case SQLITE_FCNTL_VFSNAME: {
3691 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3692 return SQLITE_OK;
3693 }
drh696b33e2012-12-06 19:01:42 +00003694 case SQLITE_FCNTL_TEMPFILENAME: {
3695 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3696 if( zTFile ){
3697 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3698 *(char**)pArg = zTFile;
3699 }
3700 return SQLITE_OK;
3701 }
danf23da962013-03-23 21:00:41 +00003702 case SQLITE_FCNTL_MMAP_SIZE: {
3703 pFile->mmapLimit = *(i64*)pArg;
danb2d3de32013-03-14 18:34:37 +00003704 return SQLITE_OK;
3705 }
drhd3d8c042012-05-29 17:02:40 +00003706#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003707 /* The pager calls this method to signal that it has done
3708 ** a rollback and that the database is therefore unchanged and
3709 ** it hence it is OK for the transaction change counter to be
3710 ** unchanged.
3711 */
3712 case SQLITE_FCNTL_DB_UNCHANGED: {
3713 ((unixFile*)id)->dbUpdate = 0;
3714 return SQLITE_OK;
3715 }
3716#endif
drhd2cb50b2009-01-09 21:41:17 +00003717#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003718 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003719 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003720 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003721 }
drhd2cb50b2009-01-09 21:41:17 +00003722#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003723 }
drh0b52b7d2011-01-26 19:46:22 +00003724 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003725}
3726
3727/*
danielk1977a3d4c882007-03-23 10:08:38 +00003728** Return the sector size in bytes of the underlying block device for
3729** the specified file. This is almost always 512 bytes, but may be
3730** larger for some devices.
3731**
3732** SQLite code assumes this function cannot fail. It also assumes that
3733** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003734** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003735** same for both.
3736*/
drh537dddf2012-10-26 13:46:24 +00003737#ifndef __QNXNTO__
3738static int unixSectorSize(sqlite3_file *NotUsed){
3739 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003740 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003741}
drh537dddf2012-10-26 13:46:24 +00003742#endif
3743
3744/*
3745** The following version of unixSectorSize() is optimized for QNX.
3746*/
3747#ifdef __QNXNTO__
3748#include <sys/dcmd_blk.h>
3749#include <sys/statvfs.h>
3750static int unixSectorSize(sqlite3_file *id){
3751 unixFile *pFile = (unixFile*)id;
3752 if( pFile->sectorSize == 0 ){
3753 struct statvfs fsInfo;
3754
3755 /* Set defaults for non-supported filesystems */
3756 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3757 pFile->deviceCharacteristics = 0;
3758 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3759 return pFile->sectorSize;
3760 }
3761
3762 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3763 pFile->sectorSize = fsInfo.f_bsize;
3764 pFile->deviceCharacteristics =
3765 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3766 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3767 ** the write succeeds */
3768 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3769 ** so it is ordered */
3770 0;
3771 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3772 pFile->sectorSize = fsInfo.f_bsize;
3773 pFile->deviceCharacteristics =
3774 /* etfs cluster size writes are atomic */
3775 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3776 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3777 ** the write succeeds */
3778 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3779 ** so it is ordered */
3780 0;
3781 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3782 pFile->sectorSize = fsInfo.f_bsize;
3783 pFile->deviceCharacteristics =
3784 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3785 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3786 ** the write succeeds */
3787 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3788 ** so it is ordered */
3789 0;
3790 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3791 pFile->sectorSize = fsInfo.f_bsize;
3792 pFile->deviceCharacteristics =
3793 /* full bitset of atomics from max sector size and smaller */
3794 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3795 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3796 ** so it is ordered */
3797 0;
3798 }else if( strstr(fsInfo.f_basetype, "dos") ){
3799 pFile->sectorSize = fsInfo.f_bsize;
3800 pFile->deviceCharacteristics =
3801 /* full bitset of atomics from max sector size and smaller */
3802 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3803 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3804 ** so it is ordered */
3805 0;
3806 }else{
3807 pFile->deviceCharacteristics =
3808 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3809 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3810 ** the write succeeds */
3811 0;
3812 }
3813 }
3814 /* Last chance verification. If the sector size isn't a multiple of 512
3815 ** then it isn't valid.*/
3816 if( pFile->sectorSize % 512 != 0 ){
3817 pFile->deviceCharacteristics = 0;
3818 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3819 }
3820 return pFile->sectorSize;
3821}
3822#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003823
danielk197790949c22007-08-17 16:50:38 +00003824/*
drhf12b3f62011-12-21 14:42:29 +00003825** Return the device characteristics for the file.
3826**
drhcb15f352011-12-23 01:04:17 +00003827** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3828** However, that choice is contraversial since technically the underlying
3829** file system does not always provide powersafe overwrites. (In other
3830** words, after a power-loss event, parts of the file that were never
3831** written might end up being altered.) However, non-PSOW behavior is very,
3832** very rare. And asserting PSOW makes a large reduction in the amount
3833** of required I/O for journaling, since a lot of padding is eliminated.
3834** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3835** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003836*/
drhf12b3f62011-12-21 14:42:29 +00003837static int unixDeviceCharacteristics(sqlite3_file *id){
3838 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003839 int rc = 0;
3840#ifdef __QNXNTO__
3841 if( p->sectorSize==0 ) unixSectorSize(id);
3842 rc = p->deviceCharacteristics;
3843#endif
drhcb15f352011-12-23 01:04:17 +00003844 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003845 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003846 }
drh537dddf2012-10-26 13:46:24 +00003847 return rc;
danielk197762079062007-08-15 17:08:46 +00003848}
3849
drhd9e5c4f2010-05-12 18:01:39 +00003850#ifndef SQLITE_OMIT_WAL
3851
3852
3853/*
drhd91c68f2010-05-14 14:52:25 +00003854** Object used to represent an shared memory buffer.
3855**
3856** When multiple threads all reference the same wal-index, each thread
3857** has its own unixShm object, but they all point to a single instance
3858** of this unixShmNode object. In other words, each wal-index is opened
3859** only once per process.
3860**
3861** Each unixShmNode object is connected to a single unixInodeInfo object.
3862** We could coalesce this object into unixInodeInfo, but that would mean
3863** every open file that does not use shared memory (in other words, most
3864** open files) would have to carry around this extra information. So
3865** the unixInodeInfo object contains a pointer to this unixShmNode object
3866** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003867**
3868** unixMutexHeld() must be true when creating or destroying
3869** this object or while reading or writing the following fields:
3870**
3871** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003872**
3873** The following fields are read-only after the object is created:
3874**
3875** fid
3876** zFilename
3877**
drhd91c68f2010-05-14 14:52:25 +00003878** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003879** unixMutexHeld() is true when reading or writing any other field
3880** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003881*/
drhd91c68f2010-05-14 14:52:25 +00003882struct unixShmNode {
3883 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003884 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003885 char *zFilename; /* Name of the mmapped file */
3886 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003887 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003888 u16 nRegion; /* Size of array apRegion */
3889 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003890 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003891 int nRef; /* Number of unixShm objects pointing to this */
3892 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003893#ifdef SQLITE_DEBUG
3894 u8 exclMask; /* Mask of exclusive locks held */
3895 u8 sharedMask; /* Mask of shared locks held */
3896 u8 nextShmId; /* Next available unixShm.id value */
3897#endif
3898};
3899
3900/*
drhd9e5c4f2010-05-12 18:01:39 +00003901** Structure used internally by this VFS to record the state of an
3902** open shared memory connection.
3903**
drhd91c68f2010-05-14 14:52:25 +00003904** The following fields are initialized when this object is created and
3905** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003906**
drhd91c68f2010-05-14 14:52:25 +00003907** unixShm.pFile
3908** unixShm.id
3909**
3910** All other fields are read/write. The unixShm.pFile->mutex must be held
3911** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003912*/
3913struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003914 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3915 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003916 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003917 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003918 u16 sharedMask; /* Mask of shared locks held */
3919 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003920};
3921
3922/*
drhd9e5c4f2010-05-12 18:01:39 +00003923** Constants used for locking
3924*/
drhbd9676c2010-06-23 17:58:38 +00003925#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003926#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003927
drhd9e5c4f2010-05-12 18:01:39 +00003928/*
drh73b64e42010-05-30 19:55:15 +00003929** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003930**
3931** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3932** otherwise.
3933*/
3934static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003935 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3936 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003937 int ofst, /* First byte of the locking range */
3938 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003939){
3940 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003941 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003942
drhd91c68f2010-05-14 14:52:25 +00003943 /* Access to the unixShmNode object is serialized by the caller */
3944 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003945
drh73b64e42010-05-30 19:55:15 +00003946 /* Shared locks never span more than one byte */
3947 assert( n==1 || lockType!=F_RDLCK );
3948
3949 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003950 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003951
drh3cb93392011-03-12 18:10:44 +00003952 if( pShmNode->h>=0 ){
3953 /* Initialize the locking parameters */
3954 memset(&f, 0, sizeof(f));
3955 f.l_type = lockType;
3956 f.l_whence = SEEK_SET;
3957 f.l_start = ofst;
3958 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003959
drh3cb93392011-03-12 18:10:44 +00003960 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3961 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3962 }
drhd9e5c4f2010-05-12 18:01:39 +00003963
3964 /* Update the global lock state and do debug tracing */
3965#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003966 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003967 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003968 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003969 if( rc==SQLITE_OK ){
3970 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003971 OSTRACE(("unlock %d ok", ofst));
3972 pShmNode->exclMask &= ~mask;
3973 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003974 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003975 OSTRACE(("read-lock %d ok", ofst));
3976 pShmNode->exclMask &= ~mask;
3977 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003978 }else{
3979 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003980 OSTRACE(("write-lock %d ok", ofst));
3981 pShmNode->exclMask |= mask;
3982 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003983 }
3984 }else{
3985 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003986 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003987 }else if( lockType==F_RDLCK ){
3988 OSTRACE(("read-lock failed"));
3989 }else{
3990 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003991 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003992 }
3993 }
drh20e1f082010-05-31 16:10:12 +00003994 OSTRACE((" - afterwards %03x,%03x\n",
3995 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003996 }
drhd9e5c4f2010-05-12 18:01:39 +00003997#endif
3998
3999 return rc;
4000}
4001
drhd9e5c4f2010-05-12 18:01:39 +00004002
4003/*
drhd91c68f2010-05-14 14:52:25 +00004004** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004005**
4006** This is not a VFS shared-memory method; it is a utility function called
4007** by VFS shared-memory methods.
4008*/
drhd91c68f2010-05-14 14:52:25 +00004009static void unixShmPurge(unixFile *pFd){
4010 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004011 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004012 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004013 int i;
drhd91c68f2010-05-14 14:52:25 +00004014 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004015 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004016 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004017 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004018 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004019 }else{
4020 sqlite3_free(p->apRegion[i]);
4021 }
dan13a3cb82010-06-11 19:04:21 +00004022 }
dan18801912010-06-14 14:07:50 +00004023 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004024 if( p->h>=0 ){
4025 robust_close(pFd, p->h, __LINE__);
4026 p->h = -1;
4027 }
drhd91c68f2010-05-14 14:52:25 +00004028 p->pInode->pShmNode = 0;
4029 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004030 }
4031}
4032
4033/*
danda9fe0c2010-07-13 18:44:03 +00004034** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004035** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004036**
drh7234c6d2010-06-19 15:10:09 +00004037** The file used to implement shared-memory is in the same directory
4038** as the open database file and has the same name as the open database
4039** file with the "-shm" suffix added. For example, if the database file
4040** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004041** for shared memory will be called "/home/user1/config.db-shm".
4042**
4043** Another approach to is to use files in /dev/shm or /dev/tmp or an
4044** some other tmpfs mount. But if a file in a different directory
4045** from the database file is used, then differing access permissions
4046** or a chroot() might cause two different processes on the same
4047** database to end up using different files for shared memory -
4048** meaning that their memory would not really be shared - resulting
4049** in database corruption. Nevertheless, this tmpfs file usage
4050** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4051** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4052** option results in an incompatible build of SQLite; builds of SQLite
4053** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4054** same database file at the same time, database corruption will likely
4055** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4056** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004057**
4058** When opening a new shared-memory file, if no other instances of that
4059** file are currently open, in this process or in other processes, then
4060** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004061**
4062** If the original database file (pDbFd) is using the "unix-excl" VFS
4063** that means that an exclusive lock is held on the database file and
4064** that no other processes are able to read or write the database. In
4065** that case, we do not really need shared memory. No shared memory
4066** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004067*/
danda9fe0c2010-07-13 18:44:03 +00004068static int unixOpenSharedMemory(unixFile *pDbFd){
4069 struct unixShm *p = 0; /* The connection to be opened */
4070 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4071 int rc; /* Result code */
4072 unixInodeInfo *pInode; /* The inode of fd */
4073 char *zShmFilename; /* Name of the file used for SHM */
4074 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004075
danda9fe0c2010-07-13 18:44:03 +00004076 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004077 p = sqlite3_malloc( sizeof(*p) );
4078 if( p==0 ) return SQLITE_NOMEM;
4079 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004080 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004081
danda9fe0c2010-07-13 18:44:03 +00004082 /* Check to see if a unixShmNode object already exists. Reuse an existing
4083 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004084 */
4085 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004086 pInode = pDbFd->pInode;
4087 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004088 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004089 struct stat sStat; /* fstat() info for database file */
4090
4091 /* Call fstat() to figure out the permissions on the database file. If
4092 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004093 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004094 */
drh3cb93392011-03-12 18:10:44 +00004095 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004096 rc = SQLITE_IOERR_FSTAT;
4097 goto shm_open_err;
4098 }
4099
drha4ced192010-07-15 18:32:40 +00004100#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004101 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004102#else
drh52bcde02012-01-03 14:50:45 +00004103 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004104#endif
drh7234c6d2010-06-19 15:10:09 +00004105 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004106 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004107 rc = SQLITE_NOMEM;
4108 goto shm_open_err;
4109 }
drh9cb5a0d2012-01-05 21:19:54 +00004110 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004111 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004112#ifdef SQLITE_SHM_DIRECTORY
4113 sqlite3_snprintf(nShmFilename, zShmFilename,
4114 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4115 (u32)sStat.st_ino, (u32)sStat.st_dev);
4116#else
drh7234c6d2010-06-19 15:10:09 +00004117 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004118 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004119#endif
drhd91c68f2010-05-14 14:52:25 +00004120 pShmNode->h = -1;
4121 pDbFd->pInode->pShmNode = pShmNode;
4122 pShmNode->pInode = pDbFd->pInode;
4123 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4124 if( pShmNode->mutex==0 ){
4125 rc = SQLITE_NOMEM;
4126 goto shm_open_err;
4127 }
drhd9e5c4f2010-05-12 18:01:39 +00004128
drh3cb93392011-03-12 18:10:44 +00004129 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004130 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004131 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004132 openFlags = O_RDONLY;
4133 pShmNode->isReadonly = 1;
4134 }
4135 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004136 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004137 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4138 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004139 }
drhac7c3ac2012-02-11 19:23:48 +00004140
4141 /* If this process is running as root, make sure that the SHM file
4142 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004143 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004144 */
drhed466822012-05-31 13:10:49 +00004145 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004146
4147 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004148 ** If not, truncate the file to zero length.
4149 */
4150 rc = SQLITE_OK;
4151 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4152 if( robust_ftruncate(pShmNode->h, 0) ){
4153 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004154 }
4155 }
drh66dfec8b2011-06-01 20:01:49 +00004156 if( rc==SQLITE_OK ){
4157 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4158 }
4159 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004160 }
drhd9e5c4f2010-05-12 18:01:39 +00004161 }
4162
drhd91c68f2010-05-14 14:52:25 +00004163 /* Make the new connection a child of the unixShmNode */
4164 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004165#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004166 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004167#endif
drhd91c68f2010-05-14 14:52:25 +00004168 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004169 pDbFd->pShm = p;
4170 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004171
4172 /* The reference count on pShmNode has already been incremented under
4173 ** the cover of the unixEnterMutex() mutex and the pointer from the
4174 ** new (struct unixShm) object to the pShmNode has been set. All that is
4175 ** left to do is to link the new object into the linked list starting
4176 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4177 ** mutex.
4178 */
4179 sqlite3_mutex_enter(pShmNode->mutex);
4180 p->pNext = pShmNode->pFirst;
4181 pShmNode->pFirst = p;
4182 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004183 return SQLITE_OK;
4184
4185 /* Jump here on any error */
4186shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004187 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004188 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004189 unixLeaveMutex();
4190 return rc;
4191}
4192
4193/*
danda9fe0c2010-07-13 18:44:03 +00004194** This function is called to obtain a pointer to region iRegion of the
4195** shared-memory associated with the database file fd. Shared-memory regions
4196** are numbered starting from zero. Each shared-memory region is szRegion
4197** bytes in size.
4198**
4199** If an error occurs, an error code is returned and *pp is set to NULL.
4200**
4201** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4202** region has not been allocated (by any client, including one running in a
4203** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4204** bExtend is non-zero and the requested shared-memory region has not yet
4205** been allocated, it is allocated by this function.
4206**
4207** If the shared-memory region has already been allocated or is allocated by
4208** this call as described above, then it is mapped into this processes
4209** address space (if it is not already), *pp is set to point to the mapped
4210** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004211*/
danda9fe0c2010-07-13 18:44:03 +00004212static int unixShmMap(
4213 sqlite3_file *fd, /* Handle open on database file */
4214 int iRegion, /* Region to retrieve */
4215 int szRegion, /* Size of regions */
4216 int bExtend, /* True to extend file if necessary */
4217 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004218){
danda9fe0c2010-07-13 18:44:03 +00004219 unixFile *pDbFd = (unixFile*)fd;
4220 unixShm *p;
4221 unixShmNode *pShmNode;
4222 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004223
danda9fe0c2010-07-13 18:44:03 +00004224 /* If the shared-memory file has not yet been opened, open it now. */
4225 if( pDbFd->pShm==0 ){
4226 rc = unixOpenSharedMemory(pDbFd);
4227 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004228 }
drhd9e5c4f2010-05-12 18:01:39 +00004229
danda9fe0c2010-07-13 18:44:03 +00004230 p = pDbFd->pShm;
4231 pShmNode = p->pShmNode;
4232 sqlite3_mutex_enter(pShmNode->mutex);
4233 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004234 assert( pShmNode->pInode==pDbFd->pInode );
4235 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4236 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004237
4238 if( pShmNode->nRegion<=iRegion ){
4239 char **apNew; /* New apRegion[] array */
4240 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4241 struct stat sStat; /* Used by fstat() */
4242
4243 pShmNode->szRegion = szRegion;
4244
drh3cb93392011-03-12 18:10:44 +00004245 if( pShmNode->h>=0 ){
4246 /* The requested region is not mapped into this processes address space.
4247 ** Check to see if it has been allocated (i.e. if the wal-index file is
4248 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004249 */
drh3cb93392011-03-12 18:10:44 +00004250 if( osFstat(pShmNode->h, &sStat) ){
4251 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004252 goto shmpage_out;
4253 }
drh3cb93392011-03-12 18:10:44 +00004254
4255 if( sStat.st_size<nByte ){
4256 /* The requested memory region does not exist. If bExtend is set to
4257 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4258 **
4259 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4260 ** the requested memory region.
4261 */
4262 if( !bExtend ) goto shmpage_out;
drh0fbb50e2012-11-13 10:54:12 +00004263#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
4264 if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
4265 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
4266 pShmNode->zFilename);
4267 goto shmpage_out;
4268 }
4269#else
drh3cb93392011-03-12 18:10:44 +00004270 if( robust_ftruncate(pShmNode->h, nByte) ){
4271 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4272 pShmNode->zFilename);
4273 goto shmpage_out;
4274 }
drh0fbb50e2012-11-13 10:54:12 +00004275#endif
drh3cb93392011-03-12 18:10:44 +00004276 }
danda9fe0c2010-07-13 18:44:03 +00004277 }
4278
4279 /* Map the requested memory region into this processes address space. */
4280 apNew = (char **)sqlite3_realloc(
4281 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4282 );
4283 if( !apNew ){
4284 rc = SQLITE_IOERR_NOMEM;
4285 goto shmpage_out;
4286 }
4287 pShmNode->apRegion = apNew;
4288 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004289 void *pMem;
4290 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004291 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004292 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004293 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004294 );
4295 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004296 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004297 goto shmpage_out;
4298 }
4299 }else{
4300 pMem = sqlite3_malloc(szRegion);
4301 if( pMem==0 ){
4302 rc = SQLITE_NOMEM;
4303 goto shmpage_out;
4304 }
4305 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004306 }
4307 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4308 pShmNode->nRegion++;
4309 }
4310 }
4311
4312shmpage_out:
4313 if( pShmNode->nRegion>iRegion ){
4314 *pp = pShmNode->apRegion[iRegion];
4315 }else{
4316 *pp = 0;
4317 }
drh66dfec8b2011-06-01 20:01:49 +00004318 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004319 sqlite3_mutex_leave(pShmNode->mutex);
4320 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004321}
4322
4323/*
drhd9e5c4f2010-05-12 18:01:39 +00004324** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004325**
4326** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4327** different here than in posix. In xShmLock(), one can go from unlocked
4328** to shared and back or from unlocked to exclusive and back. But one may
4329** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004330*/
4331static int unixShmLock(
4332 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004333 int ofst, /* First lock to acquire or release */
4334 int n, /* Number of locks to acquire or release */
4335 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004336){
drh73b64e42010-05-30 19:55:15 +00004337 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4338 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4339 unixShm *pX; /* For looping over all siblings */
4340 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4341 int rc = SQLITE_OK; /* Result code */
4342 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004343
drhd91c68f2010-05-14 14:52:25 +00004344 assert( pShmNode==pDbFd->pInode->pShmNode );
4345 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004346 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004347 assert( n>=1 );
4348 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4349 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4350 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4351 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4352 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004353 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4354 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004355
drhc99597c2010-05-31 01:41:15 +00004356 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004357 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004358 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004359 if( flags & SQLITE_SHM_UNLOCK ){
4360 u16 allMask = 0; /* Mask of locks held by siblings */
4361
4362 /* See if any siblings hold this same lock */
4363 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4364 if( pX==p ) continue;
4365 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4366 allMask |= pX->sharedMask;
4367 }
4368
4369 /* Unlock the system-level locks */
4370 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004371 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004372 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004373 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004374 }
drh73b64e42010-05-30 19:55:15 +00004375
4376 /* Undo the local locks */
4377 if( rc==SQLITE_OK ){
4378 p->exclMask &= ~mask;
4379 p->sharedMask &= ~mask;
4380 }
4381 }else if( flags & SQLITE_SHM_SHARED ){
4382 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4383
4384 /* Find out which shared locks are already held by sibling connections.
4385 ** If any sibling already holds an exclusive lock, go ahead and return
4386 ** SQLITE_BUSY.
4387 */
4388 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004389 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004390 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004391 break;
4392 }
4393 allShared |= pX->sharedMask;
4394 }
4395
4396 /* Get shared locks at the system level, if necessary */
4397 if( rc==SQLITE_OK ){
4398 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004399 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004400 }else{
drh73b64e42010-05-30 19:55:15 +00004401 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004402 }
drhd9e5c4f2010-05-12 18:01:39 +00004403 }
drh73b64e42010-05-30 19:55:15 +00004404
4405 /* Get the local shared locks */
4406 if( rc==SQLITE_OK ){
4407 p->sharedMask |= mask;
4408 }
4409 }else{
4410 /* Make sure no sibling connections hold locks that will block this
4411 ** lock. If any do, return SQLITE_BUSY right away.
4412 */
4413 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004414 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4415 rc = SQLITE_BUSY;
4416 break;
4417 }
4418 }
4419
4420 /* Get the exclusive locks at the system level. Then if successful
4421 ** also mark the local connection as being locked.
4422 */
4423 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004424 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004425 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004426 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004427 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004428 }
drhd9e5c4f2010-05-12 18:01:39 +00004429 }
4430 }
drhd91c68f2010-05-14 14:52:25 +00004431 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004432 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4433 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004434 return rc;
4435}
4436
drh286a2882010-05-20 23:51:06 +00004437/*
4438** Implement a memory barrier or memory fence on shared memory.
4439**
4440** All loads and stores begun before the barrier must complete before
4441** any load or store begun after the barrier.
4442*/
4443static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004444 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004445){
drhff828942010-06-26 21:34:06 +00004446 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004447 unixEnterMutex();
4448 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004449}
4450
dan18801912010-06-14 14:07:50 +00004451/*
danda9fe0c2010-07-13 18:44:03 +00004452** Close a connection to shared-memory. Delete the underlying
4453** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004454**
4455** If there is no shared memory associated with the connection then this
4456** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004457*/
danda9fe0c2010-07-13 18:44:03 +00004458static int unixShmUnmap(
4459 sqlite3_file *fd, /* The underlying database file */
4460 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004461){
danda9fe0c2010-07-13 18:44:03 +00004462 unixShm *p; /* The connection to be closed */
4463 unixShmNode *pShmNode; /* The underlying shared-memory file */
4464 unixShm **pp; /* For looping over sibling connections */
4465 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004466
danda9fe0c2010-07-13 18:44:03 +00004467 pDbFd = (unixFile*)fd;
4468 p = pDbFd->pShm;
4469 if( p==0 ) return SQLITE_OK;
4470 pShmNode = p->pShmNode;
4471
4472 assert( pShmNode==pDbFd->pInode->pShmNode );
4473 assert( pShmNode->pInode==pDbFd->pInode );
4474
4475 /* Remove connection p from the set of connections associated
4476 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004477 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004478 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4479 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004480
danda9fe0c2010-07-13 18:44:03 +00004481 /* Free the connection p */
4482 sqlite3_free(p);
4483 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004484 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004485
4486 /* If pShmNode->nRef has reached 0, then close the underlying
4487 ** shared-memory file, too */
4488 unixEnterMutex();
4489 assert( pShmNode->nRef>0 );
4490 pShmNode->nRef--;
4491 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004492 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004493 unixShmPurge(pDbFd);
4494 }
4495 unixLeaveMutex();
4496
4497 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004498}
drh286a2882010-05-20 23:51:06 +00004499
danda9fe0c2010-07-13 18:44:03 +00004500
drhd9e5c4f2010-05-12 18:01:39 +00004501#else
drh6b017cc2010-06-14 18:01:46 +00004502# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004503# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004504# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004505# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004506#endif /* #ifndef SQLITE_OMIT_WAL */
4507
drh734c9862008-11-28 15:37:20 +00004508/*
danaef49d72013-03-25 16:28:54 +00004509** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004510*/
danf23da962013-03-23 21:00:41 +00004511static void unixUnmapfile(unixFile *pFd){
4512 assert( pFd->nFetchOut==0 );
4513 if( pFd->pMapRegion ){
drhd1ab8062013-03-25 20:50:25 +00004514 osMunmap(pFd->pMapRegion, pFd->mmapOrigsize);
danf23da962013-03-23 21:00:41 +00004515 pFd->pMapRegion = 0;
4516 pFd->mmapSize = 0;
4517 pFd->mmapOrigsize = 0;
4518 }
4519}
dan5d8a1372013-03-19 19:28:06 +00004520
danaef49d72013-03-25 16:28:54 +00004521/*
4522** Memory map or remap the file opened by file-descriptor pFd (if the file
4523** is already mapped, the existing mapping is replaced by the new). Or, if
4524** there already exists a mapping for this file, and there are still
4525** outstanding xFetch() references to it, this function is a no-op.
4526**
4527** If parameter nByte is non-negative, then it is the requested size of
4528** the mapping to create. Otherwise, if nByte is less than zero, then the
4529** requested size is the size of the file on disk. The actual size of the
4530** created mapping is either the requested size or the value configured
4531** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
4532**
4533** SQLITE_OK is returned if no error occurs (even if the mapping is not
4534** recreated as a result of outstanding references) or an SQLite error
4535** code otherwise.
4536*/
danf23da962013-03-23 21:00:41 +00004537static int unixMapfile(unixFile *pFd, i64 nByte){
4538 i64 nMap = nByte;
4539 int rc;
daneb97b292013-03-20 14:26:59 +00004540
danf23da962013-03-23 21:00:41 +00004541 assert( nMap>=0 || pFd->nFetchOut==0 );
4542 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4543
4544 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004545 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004546 rc = osFstat(pFd->h, &statbuf);
4547 if( rc!=SQLITE_OK ){
4548 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004549 }
danf23da962013-03-23 21:00:41 +00004550 nMap = statbuf.st_size;
4551 }
4552 if( nMap>pFd->mmapLimit ){
4553 nMap = pFd->mmapLimit;
daneb97b292013-03-20 14:26:59 +00004554 }
4555
danf23da962013-03-23 21:00:41 +00004556 if( nMap!=pFd->mmapSize ){
danb7e3a322013-03-25 20:30:13 +00004557 void *pNew = 0;
dand306e1a2013-03-20 18:25:49 +00004558
danb7e3a322013-03-25 20:30:13 +00004559#if defined(__linux__) && defined(_GNU_SOURCE)
4560 if( pFd->pMapRegion && nMap>0 ){
drhd1ab8062013-03-25 20:50:25 +00004561 pNew = osMremap(pFd->pMapRegion, pFd->mmapOrigsize, nMap, MREMAP_MAYMOVE);
danb7e3a322013-03-25 20:30:13 +00004562 }else
4563#endif
4564 {
4565 unixUnmapfile(pFd);
4566 if( nMap>0 ){
4567 int flags = PROT_READ;
4568 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4569 pNew = osMmap(0, nMap, flags, MAP_SHARED, pFd->h, 0);
danf23da962013-03-23 21:00:41 +00004570 }
dan5d8a1372013-03-19 19:28:06 +00004571 }
danb7e3a322013-03-25 20:30:13 +00004572
4573 if( pNew==MAP_FAILED ){
4574 return SQLITE_IOERR_MMAP;
4575 }
4576 pFd->pMapRegion = pNew;
4577 pFd->mmapSize = nMap;
4578 pFd->mmapOrigsize = nMap;
dan5d8a1372013-03-19 19:28:06 +00004579 }
4580
danf23da962013-03-23 21:00:41 +00004581 return SQLITE_OK;
4582}
4583
danaef49d72013-03-25 16:28:54 +00004584/*
4585** If possible, return a pointer to a mapping of file fd starting at offset
4586** iOff. The mapping must be valid for at least nAmt bytes.
4587**
4588** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4589** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4590** Finally, if an error does occur, return an SQLite error code. The final
4591** value of *pp is undefined in this case.
4592**
4593** If this function does return a pointer, the caller must eventually
4594** release the reference by calling unixUnfetch().
4595*/
danf23da962013-03-23 21:00:41 +00004596static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
4597 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4598 *pp = 0;
4599
4600 if( pFd->mmapLimit>0 ){
4601 if( pFd->pMapRegion==0 ){
4602 int rc = unixMapfile(pFd, -1);
4603 if( rc!=SQLITE_OK ) return rc;
4604 }
4605 if( pFd->mmapSize >= iOff+nAmt ){
4606 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4607 pFd->nFetchOut++;
4608 }
4609 }
4610 return SQLITE_OK;
4611}
4612
danaef49d72013-03-25 16:28:54 +00004613/*
dandf737fe2013-03-25 17:00:24 +00004614** If the third argument is non-NULL, then this function releases a
4615** reference obtained by an earlier call to unixFetch(). The second
4616** argument passed to this function must be the same as the corresponding
4617** argument that was passed to the unixFetch() invocation.
4618**
4619** Or, if the third argument is NULL, then this function is being called
4620** to inform the VFS layer that, according to POSIX, any existing mapping
4621** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004622*/
dandf737fe2013-03-25 17:00:24 +00004623static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
danf23da962013-03-23 21:00:41 +00004624 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
4625
danaef49d72013-03-25 16:28:54 +00004626 /* If p==0 (unmap the entire file) then there must be no outstanding
4627 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4628 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004629 assert( (p==0)==(pFd->nFetchOut==0) );
4630
dandf737fe2013-03-25 17:00:24 +00004631 /* If p!=0, it must match the iOff value. */
4632 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4633
danf23da962013-03-23 21:00:41 +00004634 if( p ){
4635 pFd->nFetchOut--;
4636 }else{
4637 unixUnmapfile(pFd);
4638 }
4639
4640 assert( pFd->nFetchOut>=0 );
4641 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004642}
4643
4644/*
drh734c9862008-11-28 15:37:20 +00004645** Here ends the implementation of all sqlite3_file methods.
4646**
4647********************** End sqlite3_file Methods *******************************
4648******************************************************************************/
4649
4650/*
drh6b9d6dd2008-12-03 19:34:47 +00004651** This division contains definitions of sqlite3_io_methods objects that
4652** implement various file locking strategies. It also contains definitions
4653** of "finder" functions. A finder-function is used to locate the appropriate
4654** sqlite3_io_methods object for a particular database file. The pAppData
4655** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4656** the correct finder-function for that VFS.
4657**
4658** Most finder functions return a pointer to a fixed sqlite3_io_methods
4659** object. The only interesting finder-function is autolockIoFinder, which
4660** looks at the filesystem type and tries to guess the best locking
4661** strategy from that.
4662**
drh1875f7a2008-12-08 18:19:17 +00004663** For finder-funtion F, two objects are created:
4664**
4665** (1) The real finder-function named "FImpt()".
4666**
dane946c392009-08-22 11:39:46 +00004667** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004668**
4669**
4670** A pointer to the F pointer is used as the pAppData value for VFS
4671** objects. We have to do this instead of letting pAppData point
4672** directly at the finder-function since C90 rules prevent a void*
4673** from be cast into a function pointer.
4674**
drh6b9d6dd2008-12-03 19:34:47 +00004675**
drh7708e972008-11-29 00:56:52 +00004676** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004677**
drh7708e972008-11-29 00:56:52 +00004678** * A constant sqlite3_io_methods object call METHOD that has locking
4679** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4680**
4681** * An I/O method finder function called FINDER that returns a pointer
4682** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004683*/
drhd9e5c4f2010-05-12 18:01:39 +00004684#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004685static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004686 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004687 CLOSE, /* xClose */ \
4688 unixRead, /* xRead */ \
4689 unixWrite, /* xWrite */ \
4690 unixTruncate, /* xTruncate */ \
4691 unixSync, /* xSync */ \
4692 unixFileSize, /* xFileSize */ \
4693 LOCK, /* xLock */ \
4694 UNLOCK, /* xUnlock */ \
4695 CKLOCK, /* xCheckReservedLock */ \
4696 unixFileControl, /* xFileControl */ \
4697 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004698 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004699 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004700 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004701 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004702 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004703 unixFetch, /* xFetch */ \
4704 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004705}; \
drh0c2694b2009-09-03 16:23:44 +00004706static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4707 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004708 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004709} \
drh0c2694b2009-09-03 16:23:44 +00004710static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004711 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004712
4713/*
4714** Here are all of the sqlite3_io_methods objects for each of the
4715** locking strategies. Functions that return pointers to these methods
4716** are also created.
4717*/
4718IOMETHODS(
4719 posixIoFinder, /* Finder function name */
4720 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004721 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004722 unixClose, /* xClose method */
4723 unixLock, /* xLock method */
4724 unixUnlock, /* xUnlock method */
4725 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004726)
drh7708e972008-11-29 00:56:52 +00004727IOMETHODS(
4728 nolockIoFinder, /* Finder function name */
4729 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004730 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004731 nolockClose, /* xClose method */
4732 nolockLock, /* xLock method */
4733 nolockUnlock, /* xUnlock method */
4734 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004735)
drh7708e972008-11-29 00:56:52 +00004736IOMETHODS(
4737 dotlockIoFinder, /* Finder function name */
4738 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004739 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004740 dotlockClose, /* xClose method */
4741 dotlockLock, /* xLock method */
4742 dotlockUnlock, /* xUnlock method */
4743 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004744)
drh7708e972008-11-29 00:56:52 +00004745
chw78a13182009-04-07 05:35:03 +00004746#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004747IOMETHODS(
4748 flockIoFinder, /* Finder function name */
4749 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004750 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004751 flockClose, /* xClose method */
4752 flockLock, /* xLock method */
4753 flockUnlock, /* xUnlock method */
4754 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004755)
drh7708e972008-11-29 00:56:52 +00004756#endif
4757
drh6c7d5c52008-11-21 20:32:33 +00004758#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004759IOMETHODS(
4760 semIoFinder, /* Finder function name */
4761 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004762 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004763 semClose, /* xClose method */
4764 semLock, /* xLock method */
4765 semUnlock, /* xUnlock method */
4766 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004767)
aswiftaebf4132008-11-21 00:10:35 +00004768#endif
drh7708e972008-11-29 00:56:52 +00004769
drhd2cb50b2009-01-09 21:41:17 +00004770#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004771IOMETHODS(
4772 afpIoFinder, /* Finder function name */
4773 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004774 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004775 afpClose, /* xClose method */
4776 afpLock, /* xLock method */
4777 afpUnlock, /* xUnlock method */
4778 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004779)
drh715ff302008-12-03 22:32:44 +00004780#endif
4781
4782/*
4783** The proxy locking method is a "super-method" in the sense that it
4784** opens secondary file descriptors for the conch and lock files and
4785** it uses proxy, dot-file, AFP, and flock() locking methods on those
4786** secondary files. For this reason, the division that implements
4787** proxy locking is located much further down in the file. But we need
4788** to go ahead and define the sqlite3_io_methods and finder function
4789** for proxy locking here. So we forward declare the I/O methods.
4790*/
drhd2cb50b2009-01-09 21:41:17 +00004791#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004792static int proxyClose(sqlite3_file*);
4793static int proxyLock(sqlite3_file*, int);
4794static int proxyUnlock(sqlite3_file*, int);
4795static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004796IOMETHODS(
4797 proxyIoFinder, /* Finder function name */
4798 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004799 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004800 proxyClose, /* xClose method */
4801 proxyLock, /* xLock method */
4802 proxyUnlock, /* xUnlock method */
4803 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004804)
aswiftaebf4132008-11-21 00:10:35 +00004805#endif
drh7708e972008-11-29 00:56:52 +00004806
drh7ed97b92010-01-20 13:07:21 +00004807/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4808#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4809IOMETHODS(
4810 nfsIoFinder, /* Finder function name */
4811 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004812 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004813 unixClose, /* xClose method */
4814 unixLock, /* xLock method */
4815 nfsUnlock, /* xUnlock method */
4816 unixCheckReservedLock /* xCheckReservedLock method */
4817)
4818#endif
drh7708e972008-11-29 00:56:52 +00004819
drhd2cb50b2009-01-09 21:41:17 +00004820#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004821/*
drh6b9d6dd2008-12-03 19:34:47 +00004822** This "finder" function attempts to determine the best locking strategy
4823** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004824** object that implements that strategy.
4825**
4826** This is for MacOSX only.
4827*/
drh1875f7a2008-12-08 18:19:17 +00004828static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004829 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004830 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004831){
4832 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004833 const char *zFilesystem; /* Filesystem type name */
4834 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004835 } aMap[] = {
4836 { "hfs", &posixIoMethods },
4837 { "ufs", &posixIoMethods },
4838 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004839 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004840 { "webdav", &nolockIoMethods },
4841 { 0, 0 }
4842 };
4843 int i;
4844 struct statfs fsInfo;
4845 struct flock lockInfo;
4846
4847 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004848 /* If filePath==NULL that means we are dealing with a transient file
4849 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004850 return &nolockIoMethods;
4851 }
4852 if( statfs(filePath, &fsInfo) != -1 ){
4853 if( fsInfo.f_flags & MNT_RDONLY ){
4854 return &nolockIoMethods;
4855 }
4856 for(i=0; aMap[i].zFilesystem; i++){
4857 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4858 return aMap[i].pMethods;
4859 }
4860 }
4861 }
4862
4863 /* Default case. Handles, amongst others, "nfs".
4864 ** Test byte-range lock using fcntl(). If the call succeeds,
4865 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004866 */
drh7708e972008-11-29 00:56:52 +00004867 lockInfo.l_len = 1;
4868 lockInfo.l_start = 0;
4869 lockInfo.l_whence = SEEK_SET;
4870 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004871 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004872 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4873 return &nfsIoMethods;
4874 } else {
4875 return &posixIoMethods;
4876 }
drh7708e972008-11-29 00:56:52 +00004877 }else{
4878 return &dotlockIoMethods;
4879 }
4880}
drh0c2694b2009-09-03 16:23:44 +00004881static const sqlite3_io_methods
4882 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004883
drhd2cb50b2009-01-09 21:41:17 +00004884#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004885
chw78a13182009-04-07 05:35:03 +00004886#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4887/*
4888** This "finder" function attempts to determine the best locking strategy
4889** for the database file "filePath". It then returns the sqlite3_io_methods
4890** object that implements that strategy.
4891**
4892** This is for VXWorks only.
4893*/
4894static const sqlite3_io_methods *autolockIoFinderImpl(
4895 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004896 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004897){
4898 struct flock lockInfo;
4899
4900 if( !filePath ){
4901 /* If filePath==NULL that means we are dealing with a transient file
4902 ** that does not need to be locked. */
4903 return &nolockIoMethods;
4904 }
4905
4906 /* Test if fcntl() is supported and use POSIX style locks.
4907 ** Otherwise fall back to the named semaphore method.
4908 */
4909 lockInfo.l_len = 1;
4910 lockInfo.l_start = 0;
4911 lockInfo.l_whence = SEEK_SET;
4912 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004913 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004914 return &posixIoMethods;
4915 }else{
4916 return &semIoMethods;
4917 }
4918}
drh0c2694b2009-09-03 16:23:44 +00004919static const sqlite3_io_methods
4920 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004921
4922#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4923
drh7708e972008-11-29 00:56:52 +00004924/*
4925** An abstract type for a pointer to a IO method finder function:
4926*/
drh0c2694b2009-09-03 16:23:44 +00004927typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004928
aswiftaebf4132008-11-21 00:10:35 +00004929
drh734c9862008-11-28 15:37:20 +00004930/****************************************************************************
4931**************************** sqlite3_vfs methods ****************************
4932**
4933** This division contains the implementation of methods on the
4934** sqlite3_vfs object.
4935*/
4936
danielk1977a3d4c882007-03-23 10:08:38 +00004937/*
danielk1977e339d652008-06-28 11:23:00 +00004938** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004939*/
4940static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004941 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004942 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004943 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004944 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004945 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004946){
drh7708e972008-11-29 00:56:52 +00004947 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004948 unixFile *pNew = (unixFile *)pId;
4949 int rc = SQLITE_OK;
4950
drh8af6c222010-05-14 12:43:01 +00004951 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004952
dan00157392010-10-05 11:33:15 +00004953 /* Usually the path zFilename should not be a relative pathname. The
4954 ** exception is when opening the proxy "conch" file in builds that
4955 ** include the special Apple locking styles.
4956 */
dan00157392010-10-05 11:33:15 +00004957#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004958 assert( zFilename==0 || zFilename[0]=='/'
4959 || pVfs->pAppData==(void*)&autolockIoFinder );
4960#else
4961 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004962#endif
dan00157392010-10-05 11:33:15 +00004963
drhb07028f2011-10-14 21:49:18 +00004964 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004965 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004966
drh308c2a52010-05-14 11:30:18 +00004967 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004968 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004969 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004970 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004971 pNew->ctrlFlags = (u8)ctrlFlags;
4972 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4973 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004974 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004975 }
drh503a6862013-03-01 01:07:17 +00004976 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00004977 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004978 }
drh339eb0b2008-03-07 15:34:11 +00004979
drh6c7d5c52008-11-21 20:32:33 +00004980#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004981 pNew->pId = vxworksFindFileId(zFilename);
4982 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004983 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004984 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004985 }
4986#endif
4987
drhc02a43a2012-01-10 23:18:38 +00004988 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004989 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004990 }else{
drh0c2694b2009-09-03 16:23:44 +00004991 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004992#if SQLITE_ENABLE_LOCKING_STYLE
4993 /* Cache zFilename in the locking context (AFP and dotlock override) for
4994 ** proxyLock activation is possible (remote proxy is based on db name)
4995 ** zFilename remains valid until file is closed, to support */
4996 pNew->lockingContext = (void*)zFilename;
4997#endif
drhda0e7682008-07-30 15:27:54 +00004998 }
danielk1977e339d652008-06-28 11:23:00 +00004999
drh7ed97b92010-01-20 13:07:21 +00005000 if( pLockingStyle == &posixIoMethods
5001#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5002 || pLockingStyle == &nfsIoMethods
5003#endif
5004 ){
drh7708e972008-11-29 00:56:52 +00005005 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005006 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005007 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005008 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005009 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005010 ** in two scenarios:
5011 **
5012 ** (a) A call to fstat() failed.
5013 ** (b) A malloc failed.
5014 **
5015 ** Scenario (b) may only occur if the process is holding no other
5016 ** file descriptors open on the same file. If there were other file
5017 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005018 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005019 ** handle h - as it is guaranteed that no posix locks will be released
5020 ** by doing so.
5021 **
5022 ** If scenario (a) caused the error then things are not so safe. The
5023 ** implicit assumption here is that if fstat() fails, things are in
5024 ** such bad shape that dropping a lock or two doesn't matter much.
5025 */
drh0e9365c2011-03-02 02:08:13 +00005026 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005027 h = -1;
5028 }
drh7708e972008-11-29 00:56:52 +00005029 unixLeaveMutex();
5030 }
danielk1977e339d652008-06-28 11:23:00 +00005031
drhd2cb50b2009-01-09 21:41:17 +00005032#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005033 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005034 /* AFP locking uses the file path so it needs to be included in
5035 ** the afpLockingContext.
5036 */
5037 afpLockingContext *pCtx;
5038 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5039 if( pCtx==0 ){
5040 rc = SQLITE_NOMEM;
5041 }else{
5042 /* NB: zFilename exists and remains valid until the file is closed
5043 ** according to requirement F11141. So we do not need to make a
5044 ** copy of the filename. */
5045 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005046 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005047 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005048 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005049 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005050 if( rc!=SQLITE_OK ){
5051 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005052 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005053 h = -1;
5054 }
drh7708e972008-11-29 00:56:52 +00005055 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005056 }
drh7708e972008-11-29 00:56:52 +00005057 }
5058#endif
danielk1977e339d652008-06-28 11:23:00 +00005059
drh7708e972008-11-29 00:56:52 +00005060 else if( pLockingStyle == &dotlockIoMethods ){
5061 /* Dotfile locking uses the file path so it needs to be included in
5062 ** the dotlockLockingContext
5063 */
5064 char *zLockFile;
5065 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005066 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005067 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005068 zLockFile = (char *)sqlite3_malloc(nFilename);
5069 if( zLockFile==0 ){
5070 rc = SQLITE_NOMEM;
5071 }else{
5072 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005073 }
drh7708e972008-11-29 00:56:52 +00005074 pNew->lockingContext = zLockFile;
5075 }
danielk1977e339d652008-06-28 11:23:00 +00005076
drh6c7d5c52008-11-21 20:32:33 +00005077#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005078 else if( pLockingStyle == &semIoMethods ){
5079 /* Named semaphore locking uses the file path so it needs to be
5080 ** included in the semLockingContext
5081 */
5082 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005083 rc = findInodeInfo(pNew, &pNew->pInode);
5084 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5085 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005086 int n;
drh2238dcc2009-08-27 17:56:20 +00005087 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005088 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005089 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005090 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005091 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5092 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005093 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005094 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005095 }
chw97185482008-11-17 08:05:31 +00005096 }
drh7708e972008-11-29 00:56:52 +00005097 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005098 }
drh7708e972008-11-29 00:56:52 +00005099#endif
aswift5b1a2562008-08-22 00:22:35 +00005100
5101 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005102#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005103 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005104 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005105 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005106 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00005107 isDelete = 0;
5108 }
drhc02a43a2012-01-10 23:18:38 +00005109 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005110#endif
danielk1977e339d652008-06-28 11:23:00 +00005111 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005112 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005113 }else{
drh7708e972008-11-29 00:56:52 +00005114 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005115 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00005116 }
danielk1977e339d652008-06-28 11:23:00 +00005117 return rc;
drh054889e2005-11-30 03:20:31 +00005118}
drh9c06c952005-11-26 00:25:00 +00005119
danielk1977ad94b582007-08-20 06:44:22 +00005120/*
drh8b3cf822010-06-01 21:02:51 +00005121** Return the name of a directory in which to put temporary files.
5122** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005123*/
drh7234c6d2010-06-19 15:10:09 +00005124static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005125 static const char *azDirs[] = {
5126 0,
aswiftaebf4132008-11-21 00:10:35 +00005127 0,
danielk197717b90b52008-06-06 11:11:25 +00005128 "/var/tmp",
5129 "/usr/tmp",
5130 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005131 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005132 };
drh8b3cf822010-06-01 21:02:51 +00005133 unsigned int i;
5134 struct stat buf;
5135 const char *zDir = 0;
5136
5137 azDirs[0] = sqlite3_temp_directory;
5138 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005139 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005140 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005141 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005142 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005143 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005144 break;
5145 }
5146 return zDir;
5147}
5148
5149/*
5150** Create a temporary file name in zBuf. zBuf must be allocated
5151** by the calling process and must be big enough to hold at least
5152** pVfs->mxPathname bytes.
5153*/
5154static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005155 static const unsigned char zChars[] =
5156 "abcdefghijklmnopqrstuvwxyz"
5157 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5158 "0123456789";
drh41022642008-11-21 00:24:42 +00005159 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005160 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005161
5162 /* It's odd to simulate an io-error here, but really this is just
5163 ** using the io-error infrastructure to test that SQLite handles this
5164 ** function failing.
5165 */
5166 SimulateIOError( return SQLITE_IOERR );
5167
drh7234c6d2010-06-19 15:10:09 +00005168 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005169 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005170
5171 /* Check that the output buffer is large enough for the temporary file
5172 ** name. If it is not, return SQLITE_ERROR.
5173 */
drhc02a43a2012-01-10 23:18:38 +00005174 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005175 return SQLITE_ERROR;
5176 }
5177
5178 do{
drhc02a43a2012-01-10 23:18:38 +00005179 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005180 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005181 sqlite3_randomness(15, &zBuf[j]);
5182 for(i=0; i<15; i++, j++){
5183 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5184 }
5185 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005186 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005187 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005188 return SQLITE_OK;
5189}
5190
drhd2cb50b2009-01-09 21:41:17 +00005191#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005192/*
5193** Routine to transform a unixFile into a proxy-locking unixFile.
5194** Implementation in the proxy-lock division, but used by unixOpen()
5195** if SQLITE_PREFER_PROXY_LOCKING is defined.
5196*/
5197static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005198#endif
drhc66d5b62008-12-03 22:48:32 +00005199
dan08da86a2009-08-21 17:18:03 +00005200/*
5201** Search for an unused file descriptor that was opened on the database
5202** file (not a journal or master-journal file) identified by pathname
5203** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5204** argument to this function.
5205**
5206** Such a file descriptor may exist if a database connection was closed
5207** but the associated file descriptor could not be closed because some
5208** other file descriptor open on the same file is holding a file-lock.
5209** Refer to comments in the unixClose() function and the lengthy comment
5210** describing "Posix Advisory Locking" at the start of this file for
5211** further details. Also, ticket #4018.
5212**
5213** If a suitable file descriptor is found, then it is returned. If no
5214** such file descriptor is located, -1 is returned.
5215*/
dane946c392009-08-22 11:39:46 +00005216static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5217 UnixUnusedFd *pUnused = 0;
5218
5219 /* Do not search for an unused file descriptor on vxworks. Not because
5220 ** vxworks would not benefit from the change (it might, we're not sure),
5221 ** but because no way to test it is currently available. It is better
5222 ** not to risk breaking vxworks support for the sake of such an obscure
5223 ** feature. */
5224#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005225 struct stat sStat; /* Results of stat() call */
5226
5227 /* A stat() call may fail for various reasons. If this happens, it is
5228 ** almost certain that an open() call on the same path will also fail.
5229 ** For this reason, if an error occurs in the stat() call here, it is
5230 ** ignored and -1 is returned. The caller will try to open a new file
5231 ** descriptor on the same path, fail, and return an error to SQLite.
5232 **
5233 ** Even if a subsequent open() call does succeed, the consequences of
5234 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005235 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005236 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005237
5238 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005239 pInode = inodeList;
5240 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5241 || pInode->fileId.ino!=sStat.st_ino) ){
5242 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005243 }
drh8af6c222010-05-14 12:43:01 +00005244 if( pInode ){
dane946c392009-08-22 11:39:46 +00005245 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005246 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005247 pUnused = *pp;
5248 if( pUnused ){
5249 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005250 }
5251 }
5252 unixLeaveMutex();
5253 }
dane946c392009-08-22 11:39:46 +00005254#endif /* if !OS_VXWORKS */
5255 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005256}
danielk197717b90b52008-06-06 11:11:25 +00005257
5258/*
danddb0ac42010-07-14 14:48:58 +00005259** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005260** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005261** and a value suitable for passing as the third argument to open(2) is
5262** written to *pMode. If an IO error occurs, an SQLite error code is
5263** returned and the value of *pMode is not modified.
5264**
drh8c815d12012-02-13 20:16:37 +00005265** In most cases cases, this routine sets *pMode to 0, which will become
5266** an indication to robust_open() to create the file using
5267** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5268** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005269** this function queries the file-system for the permissions on the
5270** corresponding database file and sets *pMode to this value. Whenever
5271** possible, WAL and journal files are created using the same permissions
5272** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005273**
5274** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5275** original filename is unavailable. But 8_3_NAMES is only used for
5276** FAT filesystems and permissions do not matter there, so just use
5277** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005278*/
5279static int findCreateFileMode(
5280 const char *zPath, /* Path of file (possibly) being created */
5281 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005282 mode_t *pMode, /* OUT: Permissions to open file with */
5283 uid_t *pUid, /* OUT: uid to set on the file */
5284 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005285){
5286 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005287 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005288 *pUid = 0;
5289 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005290 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005291 char zDb[MAX_PATHNAME+1]; /* Database file path */
5292 int nDb; /* Number of valid bytes in zDb */
5293 struct stat sStat; /* Output of stat() on database file */
5294
dana0c989d2010-11-05 18:07:37 +00005295 /* zPath is a path to a WAL or journal file. The following block derives
5296 ** the path to the associated database file from zPath. This block handles
5297 ** the following naming conventions:
5298 **
5299 ** "<path to db>-journal"
5300 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005301 ** "<path to db>-journalNN"
5302 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005303 **
drhd337c5b2011-10-20 18:23:35 +00005304 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005305 ** used by the test_multiplex.c module.
5306 */
5307 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005308#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005309 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005310 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005311#else
5312 while( zPath[nDb]!='-' ){
5313 assert( nDb>0 );
5314 assert( zPath[nDb]!='\n' );
5315 nDb--;
5316 }
5317#endif
danddb0ac42010-07-14 14:48:58 +00005318 memcpy(zDb, zPath, nDb);
5319 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005320
drh58384f12011-07-28 00:14:45 +00005321 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005322 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005323 *pUid = sStat.st_uid;
5324 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005325 }else{
5326 rc = SQLITE_IOERR_FSTAT;
5327 }
5328 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5329 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005330 }
5331 return rc;
5332}
5333
5334/*
danielk1977ad94b582007-08-20 06:44:22 +00005335** Open the file zPath.
5336**
danielk1977b4b47412007-08-17 15:53:36 +00005337** Previously, the SQLite OS layer used three functions in place of this
5338** one:
5339**
5340** sqlite3OsOpenReadWrite();
5341** sqlite3OsOpenReadOnly();
5342** sqlite3OsOpenExclusive();
5343**
5344** These calls correspond to the following combinations of flags:
5345**
5346** ReadWrite() -> (READWRITE | CREATE)
5347** ReadOnly() -> (READONLY)
5348** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5349**
5350** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5351** true, the file was configured to be automatically deleted when the
5352** file handle closed. To achieve the same effect using this new
5353** interface, add the DELETEONCLOSE flag to those specified above for
5354** OpenExclusive().
5355*/
5356static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005357 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5358 const char *zPath, /* Pathname of file to be opened */
5359 sqlite3_file *pFile, /* The file descriptor to be filled in */
5360 int flags, /* Input flags to control the opening */
5361 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005362){
dan08da86a2009-08-21 17:18:03 +00005363 unixFile *p = (unixFile *)pFile;
5364 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005365 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005366 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005367 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005368 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005369 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005370
5371 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5372 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5373 int isCreate = (flags & SQLITE_OPEN_CREATE);
5374 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5375 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005376#if SQLITE_ENABLE_LOCKING_STYLE
5377 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5378#endif
drh3d4435b2011-08-26 20:55:50 +00005379#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5380 struct statfs fsInfo;
5381#endif
danielk1977b4b47412007-08-17 15:53:36 +00005382
danielk1977fee2d252007-08-18 10:59:19 +00005383 /* If creating a master or main-file journal, this function will open
5384 ** a file-descriptor on the directory too. The first time unixSync()
5385 ** is called the directory file descriptor will be fsync()ed and close()d.
5386 */
drh0059eae2011-08-08 23:48:40 +00005387 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005388 eType==SQLITE_OPEN_MASTER_JOURNAL
5389 || eType==SQLITE_OPEN_MAIN_JOURNAL
5390 || eType==SQLITE_OPEN_WAL
5391 ));
danielk1977fee2d252007-08-18 10:59:19 +00005392
danielk197717b90b52008-06-06 11:11:25 +00005393 /* If argument zPath is a NULL pointer, this function is required to open
5394 ** a temporary file. Use this buffer to store the file name in.
5395 */
drhc02a43a2012-01-10 23:18:38 +00005396 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005397 const char *zName = zPath;
5398
danielk1977fee2d252007-08-18 10:59:19 +00005399 /* Check the following statements are true:
5400 **
5401 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5402 ** (b) if CREATE is set, then READWRITE must also be set, and
5403 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005404 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005405 */
danielk1977b4b47412007-08-17 15:53:36 +00005406 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005407 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005408 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005409 assert(isDelete==0 || isCreate);
5410
danddb0ac42010-07-14 14:48:58 +00005411 /* The main DB, main journal, WAL file and master journal are never
5412 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005413 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5414 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5415 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005416 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005417
danielk1977fee2d252007-08-18 10:59:19 +00005418 /* Assert that the upper layer has set one of the "file-type" flags. */
5419 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5420 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5421 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005422 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005423 );
5424
dan08da86a2009-08-21 17:18:03 +00005425 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005426
dan08da86a2009-08-21 17:18:03 +00005427 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005428 UnixUnusedFd *pUnused;
5429 pUnused = findReusableFd(zName, flags);
5430 if( pUnused ){
5431 fd = pUnused->fd;
5432 }else{
dan6aa657f2009-08-24 18:57:58 +00005433 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005434 if( !pUnused ){
5435 return SQLITE_NOMEM;
5436 }
5437 }
5438 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005439
5440 /* Database filenames are double-zero terminated if they are not
5441 ** URIs with parameters. Hence, they can always be passed into
5442 ** sqlite3_uri_parameter(). */
5443 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5444
dan08da86a2009-08-21 17:18:03 +00005445 }else if( !zName ){
5446 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005447 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005448 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005449 if( rc!=SQLITE_OK ){
5450 return rc;
5451 }
5452 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005453
5454 /* Generated temporary filenames are always double-zero terminated
5455 ** for use by sqlite3_uri_parameter(). */
5456 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005457 }
5458
dan08da86a2009-08-21 17:18:03 +00005459 /* Determine the value of the flags parameter passed to POSIX function
5460 ** open(). These must be calculated even if open() is not called, as
5461 ** they may be stored as part of the file handle and used by the
5462 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005463 if( isReadonly ) openFlags |= O_RDONLY;
5464 if( isReadWrite ) openFlags |= O_RDWR;
5465 if( isCreate ) openFlags |= O_CREAT;
5466 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5467 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005468
danielk1977b4b47412007-08-17 15:53:36 +00005469 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005470 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005471 uid_t uid; /* Userid for the file */
5472 gid_t gid; /* Groupid for the file */
5473 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005474 if( rc!=SQLITE_OK ){
5475 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005476 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005477 return rc;
5478 }
drhad4f1e52011-03-04 15:43:57 +00005479 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005480 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005481 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5482 /* Failed to open the file for read/write access. Try read-only. */
5483 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005484 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005485 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005486 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005487 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005488 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005489 }
5490 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005491 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005492 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005493 }
drhac7c3ac2012-02-11 19:23:48 +00005494
5495 /* If this process is running as root and if creating a new rollback
5496 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005497 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005498 */
5499 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005500 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005501 }
danielk1977b4b47412007-08-17 15:53:36 +00005502 }
dan08da86a2009-08-21 17:18:03 +00005503 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005504 if( pOutFlags ){
5505 *pOutFlags = flags;
5506 }
5507
dane946c392009-08-22 11:39:46 +00005508 if( p->pUnused ){
5509 p->pUnused->fd = fd;
5510 p->pUnused->flags = flags;
5511 }
5512
danielk1977b4b47412007-08-17 15:53:36 +00005513 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005514#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005515 zPath = zName;
5516#else
drh036ac7f2011-08-08 23:18:05 +00005517 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005518#endif
danielk1977b4b47412007-08-17 15:53:36 +00005519 }
drh41022642008-11-21 00:24:42 +00005520#if SQLITE_ENABLE_LOCKING_STYLE
5521 else{
dan08da86a2009-08-21 17:18:03 +00005522 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005523 }
5524#endif
5525
drhda0e7682008-07-30 15:27:54 +00005526 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005527
drh7ed97b92010-01-20 13:07:21 +00005528
5529#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005530 if( fstatfs(fd, &fsInfo) == -1 ){
5531 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005532 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005533 return SQLITE_IOERR_ACCESS;
5534 }
5535 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5536 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5537 }
5538#endif
drhc02a43a2012-01-10 23:18:38 +00005539
5540 /* Set up appropriate ctrlFlags */
5541 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5542 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5543 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5544 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5545 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5546
drh7ed97b92010-01-20 13:07:21 +00005547#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005548#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005549 isAutoProxy = 1;
5550#endif
5551 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005552 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5553 int useProxy = 0;
5554
dan08da86a2009-08-21 17:18:03 +00005555 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5556 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005557 if( envforce!=NULL ){
5558 useProxy = atoi(envforce)>0;
5559 }else{
aswiftaebf4132008-11-21 00:10:35 +00005560 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005561 /* In theory, the close(fd) call is sub-optimal. If the file opened
5562 ** with fd is a database file, and there are other connections open
5563 ** on that file that are currently holding advisory locks on it,
5564 ** then the call to close() will cancel those locks. In practice,
5565 ** we're assuming that statfs() doesn't fail very often. At least
5566 ** not while other file descriptors opened by the same process on
5567 ** the same file are working. */
5568 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005569 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005570 rc = SQLITE_IOERR_ACCESS;
5571 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005572 }
5573 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5574 }
5575 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005576 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005577 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005578 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005579 if( rc!=SQLITE_OK ){
5580 /* Use unixClose to clean up the resources added in fillInUnixFile
5581 ** and clear all the structure's references. Specifically,
5582 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5583 */
5584 unixClose(pFile);
5585 return rc;
5586 }
aswiftaebf4132008-11-21 00:10:35 +00005587 }
dane946c392009-08-22 11:39:46 +00005588 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005589 }
5590 }
5591#endif
5592
drhc02a43a2012-01-10 23:18:38 +00005593 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5594
dane946c392009-08-22 11:39:46 +00005595open_finished:
5596 if( rc!=SQLITE_OK ){
5597 sqlite3_free(p->pUnused);
5598 }
5599 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005600}
5601
dane946c392009-08-22 11:39:46 +00005602
danielk1977b4b47412007-08-17 15:53:36 +00005603/*
danielk1977fee2d252007-08-18 10:59:19 +00005604** Delete the file at zPath. If the dirSync argument is true, fsync()
5605** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005606*/
drh6b9d6dd2008-12-03 19:34:47 +00005607static int unixDelete(
5608 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5609 const char *zPath, /* Name of file to be deleted */
5610 int dirSync /* If true, fsync() directory after deleting file */
5611){
danielk1977fee2d252007-08-18 10:59:19 +00005612 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005613 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005614 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005615 if( osUnlink(zPath)==(-1) ){
5616 if( errno==ENOENT ){
5617 rc = SQLITE_IOERR_DELETE_NOENT;
5618 }else{
drhb4308162012-11-09 21:40:02 +00005619 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005620 }
drhb4308162012-11-09 21:40:02 +00005621 return rc;
drh5d4feff2010-07-14 01:45:22 +00005622 }
danielk1977d39fa702008-10-16 13:27:40 +00005623#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005624 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005625 int fd;
drh90315a22011-08-10 01:52:12 +00005626 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005627 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005628#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005629 if( fsync(fd)==-1 )
5630#else
5631 if( fsync(fd) )
5632#endif
5633 {
dane18d4952011-02-21 11:46:24 +00005634 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005635 }
drh0e9365c2011-03-02 02:08:13 +00005636 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005637 }else if( rc==SQLITE_CANTOPEN ){
5638 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005639 }
5640 }
danielk1977d138dd82008-10-15 16:02:48 +00005641#endif
danielk1977fee2d252007-08-18 10:59:19 +00005642 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005643}
5644
danielk197790949c22007-08-17 16:50:38 +00005645/*
mistachkin48864df2013-03-21 21:20:32 +00005646** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005647** test performed depends on the value of flags:
5648**
5649** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5650** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5651** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5652**
5653** Otherwise return 0.
5654*/
danielk1977861f7452008-06-05 11:39:11 +00005655static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005656 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5657 const char *zPath, /* Path of the file to examine */
5658 int flags, /* What do we want to learn about the zPath file? */
5659 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005660){
rse25c0d1a2007-09-20 08:38:14 +00005661 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005662 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005663 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005664 switch( flags ){
5665 case SQLITE_ACCESS_EXISTS:
5666 amode = F_OK;
5667 break;
5668 case SQLITE_ACCESS_READWRITE:
5669 amode = W_OK|R_OK;
5670 break;
drh50d3f902007-08-27 21:10:36 +00005671 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005672 amode = R_OK;
5673 break;
5674
5675 default:
5676 assert(!"Invalid flags argument");
5677 }
drh99ab3b12011-03-02 15:09:07 +00005678 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005679 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5680 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005681 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005682 *pResOut = 0;
5683 }
5684 }
danielk1977861f7452008-06-05 11:39:11 +00005685 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005686}
5687
danielk1977b4b47412007-08-17 15:53:36 +00005688
5689/*
5690** Turn a relative pathname into a full pathname. The relative path
5691** is stored as a nul-terminated string in the buffer pointed to by
5692** zPath.
5693**
5694** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5695** (in this case, MAX_PATHNAME bytes). The full-path is written to
5696** this buffer before returning.
5697*/
danielk1977adfb9b02007-09-17 07:02:56 +00005698static int unixFullPathname(
5699 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5700 const char *zPath, /* Possibly relative input path */
5701 int nOut, /* Size of output buffer in bytes */
5702 char *zOut /* Output buffer */
5703){
danielk1977843e65f2007-09-01 16:16:15 +00005704
5705 /* It's odd to simulate an io-error here, but really this is just
5706 ** using the io-error infrastructure to test that SQLite handles this
5707 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005708 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005709 */
5710 SimulateIOError( return SQLITE_ERROR );
5711
drh153c62c2007-08-24 03:51:33 +00005712 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005713 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005714
drh3c7f2dc2007-12-06 13:26:20 +00005715 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005716 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005717 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005718 }else{
5719 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005720 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005721 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005722 }
drhea678832008-12-10 19:26:22 +00005723 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005724 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005725 }
5726 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005727}
5728
drh0ccebe72005-06-07 22:22:50 +00005729
drh761df872006-12-21 01:29:22 +00005730#ifndef SQLITE_OMIT_LOAD_EXTENSION
5731/*
5732** Interfaces for opening a shared library, finding entry points
5733** within the shared library, and closing the shared library.
5734*/
5735#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005736static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5737 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005738 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5739}
danielk197795c8a542007-09-01 06:51:27 +00005740
5741/*
5742** SQLite calls this function immediately after a call to unixDlSym() or
5743** unixDlOpen() fails (returns a null pointer). If a more detailed error
5744** message is available, it is written to zBufOut. If no error message
5745** is available, zBufOut is left unmodified and SQLite uses a default
5746** error message.
5747*/
danielk1977397d65f2008-11-19 11:35:39 +00005748static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005749 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005750 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005751 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005752 zErr = dlerror();
5753 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005754 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005755 }
drh6c7d5c52008-11-21 20:32:33 +00005756 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005757}
drh1875f7a2008-12-08 18:19:17 +00005758static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5759 /*
5760 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5761 ** cast into a pointer to a function. And yet the library dlsym() routine
5762 ** returns a void* which is really a pointer to a function. So how do we
5763 ** use dlsym() with -pedantic-errors?
5764 **
5765 ** Variable x below is defined to be a pointer to a function taking
5766 ** parameters void* and const char* and returning a pointer to a function.
5767 ** We initialize x by assigning it a pointer to the dlsym() function.
5768 ** (That assignment requires a cast.) Then we call the function that
5769 ** x points to.
5770 **
5771 ** This work-around is unlikely to work correctly on any system where
5772 ** you really cannot cast a function pointer into void*. But then, on the
5773 ** other hand, dlsym() will not work on such a system either, so we have
5774 ** not really lost anything.
5775 */
5776 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005777 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005778 x = (void(*(*)(void*,const char*))(void))dlsym;
5779 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005780}
danielk1977397d65f2008-11-19 11:35:39 +00005781static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5782 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005783 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005784}
danielk1977b4b47412007-08-17 15:53:36 +00005785#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5786 #define unixDlOpen 0
5787 #define unixDlError 0
5788 #define unixDlSym 0
5789 #define unixDlClose 0
5790#endif
5791
5792/*
danielk197790949c22007-08-17 16:50:38 +00005793** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005794*/
danielk1977397d65f2008-11-19 11:35:39 +00005795static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5796 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005797 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005798
drhbbd42a62004-05-22 17:41:58 +00005799 /* We have to initialize zBuf to prevent valgrind from reporting
5800 ** errors. The reports issued by valgrind are incorrect - we would
5801 ** prefer that the randomness be increased by making use of the
5802 ** uninitialized space in zBuf - but valgrind errors tend to worry
5803 ** some users. Rather than argue, it seems easier just to initialize
5804 ** the whole array and silence valgrind, even if that means less randomness
5805 ** in the random seed.
5806 **
5807 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005808 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005809 ** tests repeatable.
5810 */
danielk1977b4b47412007-08-17 15:53:36 +00005811 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005812#if !defined(SQLITE_TEST)
5813 {
drhc18b4042012-02-10 03:10:27 +00005814 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005815 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005816 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005817 time_t t;
5818 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005819 memcpy(zBuf, &t, sizeof(t));
5820 pid = getpid();
5821 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005822 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005823 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005824 }else{
drhc18b4042012-02-10 03:10:27 +00005825 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005826 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005827 }
drhbbd42a62004-05-22 17:41:58 +00005828 }
5829#endif
drh72cbd072008-10-14 17:58:38 +00005830 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005831}
5832
danielk1977b4b47412007-08-17 15:53:36 +00005833
drhbbd42a62004-05-22 17:41:58 +00005834/*
5835** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005836** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005837** The return value is the number of microseconds of sleep actually
5838** requested from the underlying operating system, a number which
5839** might be greater than or equal to the argument, but not less
5840** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005841*/
danielk1977397d65f2008-11-19 11:35:39 +00005842static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005843#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005844 struct timespec sp;
5845
5846 sp.tv_sec = microseconds / 1000000;
5847 sp.tv_nsec = (microseconds % 1000000) * 1000;
5848 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005849 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005850 return microseconds;
5851#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005852 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005853 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005854 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005855#else
danielk1977b4b47412007-08-17 15:53:36 +00005856 int seconds = (microseconds+999999)/1000000;
5857 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005858 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005859 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005860#endif
drh88f474a2006-01-02 20:00:12 +00005861}
5862
5863/*
drh6b9d6dd2008-12-03 19:34:47 +00005864** The following variable, if set to a non-zero value, is interpreted as
5865** the number of seconds since 1970 and is used to set the result of
5866** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005867*/
5868#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005869int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005870#endif
5871
5872/*
drhb7e8ea22010-05-03 14:32:30 +00005873** Find the current time (in Universal Coordinated Time). Write into *piNow
5874** the current time and date as a Julian Day number times 86_400_000. In
5875** other words, write into *piNow the number of milliseconds since the Julian
5876** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5877** proleptic Gregorian calendar.
5878**
drh31702252011-10-12 23:13:43 +00005879** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5880** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005881*/
5882static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5883 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005884 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005885#if defined(NO_GETTOD)
5886 time_t t;
5887 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005888 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005889#elif OS_VXWORKS
5890 struct timespec sNow;
5891 clock_gettime(CLOCK_REALTIME, &sNow);
5892 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5893#else
5894 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005895 if( gettimeofday(&sNow, 0)==0 ){
5896 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5897 }else{
5898 rc = SQLITE_ERROR;
5899 }
drhb7e8ea22010-05-03 14:32:30 +00005900#endif
5901
5902#ifdef SQLITE_TEST
5903 if( sqlite3_current_time ){
5904 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5905 }
5906#endif
5907 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005908 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005909}
5910
5911/*
drhbbd42a62004-05-22 17:41:58 +00005912** Find the current time (in Universal Coordinated Time). Write the
5913** current time and date as a Julian Day number into *prNow and
5914** return 0. Return 1 if the time and date cannot be found.
5915*/
danielk1977397d65f2008-11-19 11:35:39 +00005916static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005917 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005918 int rc;
drhff828942010-06-26 21:34:06 +00005919 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005920 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005921 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005922 return rc;
drhbbd42a62004-05-22 17:41:58 +00005923}
danielk1977b4b47412007-08-17 15:53:36 +00005924
drh6b9d6dd2008-12-03 19:34:47 +00005925/*
5926** We added the xGetLastError() method with the intention of providing
5927** better low-level error messages when operating-system problems come up
5928** during SQLite operation. But so far, none of that has been implemented
5929** in the core. So this routine is never called. For now, it is merely
5930** a place-holder.
5931*/
danielk1977397d65f2008-11-19 11:35:39 +00005932static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5933 UNUSED_PARAMETER(NotUsed);
5934 UNUSED_PARAMETER(NotUsed2);
5935 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005936 return 0;
5937}
5938
drhf2424c52010-04-26 00:04:55 +00005939
5940/*
drh734c9862008-11-28 15:37:20 +00005941************************ End of sqlite3_vfs methods ***************************
5942******************************************************************************/
5943
drh715ff302008-12-03 22:32:44 +00005944/******************************************************************************
5945************************** Begin Proxy Locking ********************************
5946**
5947** Proxy locking is a "uber-locking-method" in this sense: It uses the
5948** other locking methods on secondary lock files. Proxy locking is a
5949** meta-layer over top of the primitive locking implemented above. For
5950** this reason, the division that implements of proxy locking is deferred
5951** until late in the file (here) after all of the other I/O methods have
5952** been defined - so that the primitive locking methods are available
5953** as services to help with the implementation of proxy locking.
5954**
5955****
5956**
5957** The default locking schemes in SQLite use byte-range locks on the
5958** database file to coordinate safe, concurrent access by multiple readers
5959** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5960** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5961** as POSIX read & write locks over fixed set of locations (via fsctl),
5962** on AFP and SMB only exclusive byte-range locks are available via fsctl
5963** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5964** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5965** address in the shared range is taken for a SHARED lock, the entire
5966** shared range is taken for an EXCLUSIVE lock):
5967**
drhf2f105d2012-08-20 15:53:54 +00005968** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00005969** RESERVED_BYTE 0x40000001
5970** SHARED_RANGE 0x40000002 -> 0x40000200
5971**
5972** This works well on the local file system, but shows a nearly 100x
5973** slowdown in read performance on AFP because the AFP client disables
5974** the read cache when byte-range locks are present. Enabling the read
5975** cache exposes a cache coherency problem that is present on all OS X
5976** supported network file systems. NFS and AFP both observe the
5977** close-to-open semantics for ensuring cache coherency
5978** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5979** address the requirements for concurrent database access by multiple
5980** readers and writers
5981** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5982**
5983** To address the performance and cache coherency issues, proxy file locking
5984** changes the way database access is controlled by limiting access to a
5985** single host at a time and moving file locks off of the database file
5986** and onto a proxy file on the local file system.
5987**
5988**
5989** Using proxy locks
5990** -----------------
5991**
5992** C APIs
5993**
5994** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5995** <proxy_path> | ":auto:");
5996** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5997**
5998**
5999** SQL pragmas
6000**
6001** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6002** PRAGMA [database.]lock_proxy_file
6003**
6004** Specifying ":auto:" means that if there is a conch file with a matching
6005** host ID in it, the proxy path in the conch file will be used, otherwise
6006** a proxy path based on the user's temp dir
6007** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6008** actual proxy file name is generated from the name and path of the
6009** database file. For example:
6010**
6011** For database path "/Users/me/foo.db"
6012** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6013**
6014** Once a lock proxy is configured for a database connection, it can not
6015** be removed, however it may be switched to a different proxy path via
6016** the above APIs (assuming the conch file is not being held by another
6017** connection or process).
6018**
6019**
6020** How proxy locking works
6021** -----------------------
6022**
6023** Proxy file locking relies primarily on two new supporting files:
6024**
6025** * conch file to limit access to the database file to a single host
6026** at a time
6027**
6028** * proxy file to act as a proxy for the advisory locks normally
6029** taken on the database
6030**
6031** The conch file - to use a proxy file, sqlite must first "hold the conch"
6032** by taking an sqlite-style shared lock on the conch file, reading the
6033** contents and comparing the host's unique host ID (see below) and lock
6034** proxy path against the values stored in the conch. The conch file is
6035** stored in the same directory as the database file and the file name
6036** is patterned after the database file name as ".<databasename>-conch".
6037** If the conch file does not exist, or it's contents do not match the
6038** host ID and/or proxy path, then the lock is escalated to an exclusive
6039** lock and the conch file contents is updated with the host ID and proxy
6040** path and the lock is downgraded to a shared lock again. If the conch
6041** is held by another process (with a shared lock), the exclusive lock
6042** will fail and SQLITE_BUSY is returned.
6043**
6044** The proxy file - a single-byte file used for all advisory file locks
6045** normally taken on the database file. This allows for safe sharing
6046** of the database file for multiple readers and writers on the same
6047** host (the conch ensures that they all use the same local lock file).
6048**
drh715ff302008-12-03 22:32:44 +00006049** Requesting the lock proxy does not immediately take the conch, it is
6050** only taken when the first request to lock database file is made.
6051** This matches the semantics of the traditional locking behavior, where
6052** opening a connection to a database file does not take a lock on it.
6053** The shared lock and an open file descriptor are maintained until
6054** the connection to the database is closed.
6055**
6056** The proxy file and the lock file are never deleted so they only need
6057** to be created the first time they are used.
6058**
6059** Configuration options
6060** ---------------------
6061**
6062** SQLITE_PREFER_PROXY_LOCKING
6063**
6064** Database files accessed on non-local file systems are
6065** automatically configured for proxy locking, lock files are
6066** named automatically using the same logic as
6067** PRAGMA lock_proxy_file=":auto:"
6068**
6069** SQLITE_PROXY_DEBUG
6070**
6071** Enables the logging of error messages during host id file
6072** retrieval and creation
6073**
drh715ff302008-12-03 22:32:44 +00006074** LOCKPROXYDIR
6075**
6076** Overrides the default directory used for lock proxy files that
6077** are named automatically via the ":auto:" setting
6078**
6079** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6080**
6081** Permissions to use when creating a directory for storing the
6082** lock proxy files, only used when LOCKPROXYDIR is not set.
6083**
6084**
6085** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6086** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6087** force proxy locking to be used for every database file opened, and 0
6088** will force automatic proxy locking to be disabled for all database
6089** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6090** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6091*/
6092
6093/*
6094** Proxy locking is only available on MacOSX
6095*/
drhd2cb50b2009-01-09 21:41:17 +00006096#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006097
drh715ff302008-12-03 22:32:44 +00006098/*
6099** The proxyLockingContext has the path and file structures for the remote
6100** and local proxy files in it
6101*/
6102typedef struct proxyLockingContext proxyLockingContext;
6103struct proxyLockingContext {
6104 unixFile *conchFile; /* Open conch file */
6105 char *conchFilePath; /* Name of the conch file */
6106 unixFile *lockProxy; /* Open proxy lock file */
6107 char *lockProxyPath; /* Name of the proxy lock file */
6108 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006109 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006110 void *oldLockingContext; /* Original lockingcontext to restore on close */
6111 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6112};
6113
drh7ed97b92010-01-20 13:07:21 +00006114/*
6115** The proxy lock file path for the database at dbPath is written into lPath,
6116** which must point to valid, writable memory large enough for a maxLen length
6117** file path.
drh715ff302008-12-03 22:32:44 +00006118*/
drh715ff302008-12-03 22:32:44 +00006119static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6120 int len;
6121 int dbLen;
6122 int i;
6123
6124#ifdef LOCKPROXYDIR
6125 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6126#else
6127# ifdef _CS_DARWIN_USER_TEMP_DIR
6128 {
drh7ed97b92010-01-20 13:07:21 +00006129 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006130 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6131 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006132 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006133 }
drh7ed97b92010-01-20 13:07:21 +00006134 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006135 }
6136# else
6137 len = strlcpy(lPath, "/tmp/", maxLen);
6138# endif
6139#endif
6140
6141 if( lPath[len-1]!='/' ){
6142 len = strlcat(lPath, "/", maxLen);
6143 }
6144
6145 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006146 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006147 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006148 char c = dbPath[i];
6149 lPath[i+len] = (c=='/')?'_':c;
6150 }
6151 lPath[i+len]='\0';
6152 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006153 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006154 return SQLITE_OK;
6155}
6156
drh7ed97b92010-01-20 13:07:21 +00006157/*
6158 ** Creates the lock file and any missing directories in lockPath
6159 */
6160static int proxyCreateLockPath(const char *lockPath){
6161 int i, len;
6162 char buf[MAXPATHLEN];
6163 int start = 0;
6164
6165 assert(lockPath!=NULL);
6166 /* try to create all the intermediate directories */
6167 len = (int)strlen(lockPath);
6168 buf[0] = lockPath[0];
6169 for( i=1; i<len; i++ ){
6170 if( lockPath[i] == '/' && (i - start > 0) ){
6171 /* only mkdir if leaf dir != "." or "/" or ".." */
6172 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6173 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6174 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006175 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006176 int err=errno;
6177 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006178 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006179 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006180 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006181 return err;
6182 }
6183 }
6184 }
6185 start=i+1;
6186 }
6187 buf[i] = lockPath[i];
6188 }
drh308c2a52010-05-14 11:30:18 +00006189 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006190 return 0;
6191}
6192
drh715ff302008-12-03 22:32:44 +00006193/*
6194** Create a new VFS file descriptor (stored in memory obtained from
6195** sqlite3_malloc) and open the file named "path" in the file descriptor.
6196**
6197** The caller is responsible not only for closing the file descriptor
6198** but also for freeing the memory associated with the file descriptor.
6199*/
drh7ed97b92010-01-20 13:07:21 +00006200static int proxyCreateUnixFile(
6201 const char *path, /* path for the new unixFile */
6202 unixFile **ppFile, /* unixFile created and returned by ref */
6203 int islockfile /* if non zero missing dirs will be created */
6204) {
6205 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006206 unixFile *pNew;
6207 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006208 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006209 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006210 int terrno = 0;
6211 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006212
drh7ed97b92010-01-20 13:07:21 +00006213 /* 1. first try to open/create the file
6214 ** 2. if that fails, and this is a lock file (not-conch), try creating
6215 ** the parent directories and then try again.
6216 ** 3. if that fails, try to open the file read-only
6217 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6218 */
6219 pUnused = findReusableFd(path, openFlags);
6220 if( pUnused ){
6221 fd = pUnused->fd;
6222 }else{
6223 pUnused = sqlite3_malloc(sizeof(*pUnused));
6224 if( !pUnused ){
6225 return SQLITE_NOMEM;
6226 }
6227 }
6228 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006229 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006230 terrno = errno;
6231 if( fd<0 && errno==ENOENT && islockfile ){
6232 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006233 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006234 }
6235 }
6236 }
6237 if( fd<0 ){
6238 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006239 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006240 terrno = errno;
6241 }
6242 if( fd<0 ){
6243 if( islockfile ){
6244 return SQLITE_BUSY;
6245 }
6246 switch (terrno) {
6247 case EACCES:
6248 return SQLITE_PERM;
6249 case EIO:
6250 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6251 default:
drh9978c972010-02-23 17:36:32 +00006252 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006253 }
6254 }
6255
6256 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6257 if( pNew==NULL ){
6258 rc = SQLITE_NOMEM;
6259 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006260 }
6261 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006262 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006263 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006264 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006265 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006266 pUnused->fd = fd;
6267 pUnused->flags = openFlags;
6268 pNew->pUnused = pUnused;
6269
drhc02a43a2012-01-10 23:18:38 +00006270 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006271 if( rc==SQLITE_OK ){
6272 *ppFile = pNew;
6273 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006274 }
drh7ed97b92010-01-20 13:07:21 +00006275end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006276 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006277 sqlite3_free(pNew);
6278 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006279 return rc;
6280}
6281
drh7ed97b92010-01-20 13:07:21 +00006282#ifdef SQLITE_TEST
6283/* simulate multiple hosts by creating unique hostid file paths */
6284int sqlite3_hostid_num = 0;
6285#endif
6286
6287#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6288
drh0ab216a2010-07-02 17:10:40 +00006289/* Not always defined in the headers as it ought to be */
6290extern int gethostuuid(uuid_t id, const struct timespec *wait);
6291
drh7ed97b92010-01-20 13:07:21 +00006292/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6293** bytes of writable memory.
6294*/
6295static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006296 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6297 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006298#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6299 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006300 {
6301 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6302 if( gethostuuid(pHostID, &timeout) ){
6303 int err = errno;
6304 if( pError ){
6305 *pError = err;
6306 }
6307 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006308 }
drh7ed97b92010-01-20 13:07:21 +00006309 }
drh3d4435b2011-08-26 20:55:50 +00006310#else
6311 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006312#endif
drh7ed97b92010-01-20 13:07:21 +00006313#ifdef SQLITE_TEST
6314 /* simulate multiple hosts by creating unique hostid file paths */
6315 if( sqlite3_hostid_num != 0){
6316 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6317 }
6318#endif
6319
6320 return SQLITE_OK;
6321}
6322
6323/* The conch file contains the header, host id and lock file path
6324 */
6325#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6326#define PROXY_HEADERLEN 1 /* conch file header length */
6327#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6328#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6329
6330/*
6331** Takes an open conch file, copies the contents to a new path and then moves
6332** it back. The newly created file's file descriptor is assigned to the
6333** conch file structure and finally the original conch file descriptor is
6334** closed. Returns zero if successful.
6335*/
6336static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6337 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6338 unixFile *conchFile = pCtx->conchFile;
6339 char tPath[MAXPATHLEN];
6340 char buf[PROXY_MAXCONCHLEN];
6341 char *cPath = pCtx->conchFilePath;
6342 size_t readLen = 0;
6343 size_t pathLen = 0;
6344 char errmsg[64] = "";
6345 int fd = -1;
6346 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006347 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006348
6349 /* create a new path by replace the trailing '-conch' with '-break' */
6350 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6351 if( pathLen>MAXPATHLEN || pathLen<6 ||
6352 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006353 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006354 goto end_breaklock;
6355 }
6356 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006357 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006358 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006359 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006360 goto end_breaklock;
6361 }
6362 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006363 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006364 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006365 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006366 goto end_breaklock;
6367 }
drhe562be52011-03-02 18:01:10 +00006368 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006369 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006370 goto end_breaklock;
6371 }
6372 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006373 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006374 goto end_breaklock;
6375 }
6376 rc = 0;
6377 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006378 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006379 conchFile->h = fd;
6380 conchFile->openFlags = O_RDWR | O_CREAT;
6381
6382end_breaklock:
6383 if( rc ){
6384 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006385 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006386 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006387 }
6388 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6389 }
6390 return rc;
6391}
6392
6393/* Take the requested lock on the conch file and break a stale lock if the
6394** host id matches.
6395*/
6396static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6397 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6398 unixFile *conchFile = pCtx->conchFile;
6399 int rc = SQLITE_OK;
6400 int nTries = 0;
6401 struct timespec conchModTime;
6402
drh3d4435b2011-08-26 20:55:50 +00006403 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006404 do {
6405 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6406 nTries ++;
6407 if( rc==SQLITE_BUSY ){
6408 /* If the lock failed (busy):
6409 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6410 * 2nd try: fail if the mod time changed or host id is different, wait
6411 * 10 sec and try again
6412 * 3rd try: break the lock unless the mod time has changed.
6413 */
6414 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006415 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006416 pFile->lastErrno = errno;
6417 return SQLITE_IOERR_LOCK;
6418 }
6419
6420 if( nTries==1 ){
6421 conchModTime = buf.st_mtimespec;
6422 usleep(500000); /* wait 0.5 sec and try the lock again*/
6423 continue;
6424 }
6425
6426 assert( nTries>1 );
6427 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6428 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6429 return SQLITE_BUSY;
6430 }
6431
6432 if( nTries==2 ){
6433 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006434 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006435 if( len<0 ){
6436 pFile->lastErrno = errno;
6437 return SQLITE_IOERR_LOCK;
6438 }
6439 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6440 /* don't break the lock if the host id doesn't match */
6441 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6442 return SQLITE_BUSY;
6443 }
6444 }else{
6445 /* don't break the lock on short read or a version mismatch */
6446 return SQLITE_BUSY;
6447 }
6448 usleep(10000000); /* wait 10 sec and try the lock again */
6449 continue;
6450 }
6451
6452 assert( nTries==3 );
6453 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6454 rc = SQLITE_OK;
6455 if( lockType==EXCLUSIVE_LOCK ){
6456 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6457 }
6458 if( !rc ){
6459 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6460 }
6461 }
6462 }
6463 } while( rc==SQLITE_BUSY && nTries<3 );
6464
6465 return rc;
6466}
6467
6468/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006469** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6470** lockPath means that the lockPath in the conch file will be used if the
6471** host IDs match, or a new lock path will be generated automatically
6472** and written to the conch file.
6473*/
6474static int proxyTakeConch(unixFile *pFile){
6475 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6476
drh7ed97b92010-01-20 13:07:21 +00006477 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006478 return SQLITE_OK;
6479 }else{
6480 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006481 uuid_t myHostID;
6482 int pError = 0;
6483 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006484 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006485 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006486 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006487 int createConch = 0;
6488 int hostIdMatch = 0;
6489 int readLen = 0;
6490 int tryOldLockPath = 0;
6491 int forceNewLockPath = 0;
6492
drh308c2a52010-05-14 11:30:18 +00006493 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6494 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006495
drh7ed97b92010-01-20 13:07:21 +00006496 rc = proxyGetHostID(myHostID, &pError);
6497 if( (rc&0xff)==SQLITE_IOERR ){
6498 pFile->lastErrno = pError;
6499 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006500 }
drh7ed97b92010-01-20 13:07:21 +00006501 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006502 if( rc!=SQLITE_OK ){
6503 goto end_takeconch;
6504 }
drh7ed97b92010-01-20 13:07:21 +00006505 /* read the existing conch file */
6506 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6507 if( readLen<0 ){
6508 /* I/O error: lastErrno set by seekAndRead */
6509 pFile->lastErrno = conchFile->lastErrno;
6510 rc = SQLITE_IOERR_READ;
6511 goto end_takeconch;
6512 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6513 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6514 /* a short read or version format mismatch means we need to create a new
6515 ** conch file.
6516 */
6517 createConch = 1;
6518 }
6519 /* if the host id matches and the lock path already exists in the conch
6520 ** we'll try to use the path there, if we can't open that path, we'll
6521 ** retry with a new auto-generated path
6522 */
6523 do { /* in case we need to try again for an :auto: named lock file */
6524
6525 if( !createConch && !forceNewLockPath ){
6526 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6527 PROXY_HOSTIDLEN);
6528 /* if the conch has data compare the contents */
6529 if( !pCtx->lockProxyPath ){
6530 /* for auto-named local lock file, just check the host ID and we'll
6531 ** use the local lock file path that's already in there
6532 */
6533 if( hostIdMatch ){
6534 size_t pathLen = (readLen - PROXY_PATHINDEX);
6535
6536 if( pathLen>=MAXPATHLEN ){
6537 pathLen=MAXPATHLEN-1;
6538 }
6539 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6540 lockPath[pathLen] = 0;
6541 tempLockPath = lockPath;
6542 tryOldLockPath = 1;
6543 /* create a copy of the lock path if the conch is taken */
6544 goto end_takeconch;
6545 }
6546 }else if( hostIdMatch
6547 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6548 readLen-PROXY_PATHINDEX)
6549 ){
6550 /* conch host and lock path match */
6551 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006552 }
drh7ed97b92010-01-20 13:07:21 +00006553 }
6554
6555 /* if the conch isn't writable and doesn't match, we can't take it */
6556 if( (conchFile->openFlags&O_RDWR) == 0 ){
6557 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006558 goto end_takeconch;
6559 }
drh7ed97b92010-01-20 13:07:21 +00006560
6561 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006562 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006563 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6564 tempLockPath = lockPath;
6565 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006566 }
drh7ed97b92010-01-20 13:07:21 +00006567
6568 /* update conch with host and path (this will fail if other process
6569 ** has a shared lock already), if the host id matches, use the big
6570 ** stick.
drh715ff302008-12-03 22:32:44 +00006571 */
drh7ed97b92010-01-20 13:07:21 +00006572 futimes(conchFile->h, NULL);
6573 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006574 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006575 /* We are trying for an exclusive lock but another thread in this
6576 ** same process is still holding a shared lock. */
6577 rc = SQLITE_BUSY;
6578 } else {
6579 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006580 }
drh715ff302008-12-03 22:32:44 +00006581 }else{
drh7ed97b92010-01-20 13:07:21 +00006582 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006583 }
drh7ed97b92010-01-20 13:07:21 +00006584 if( rc==SQLITE_OK ){
6585 char writeBuffer[PROXY_MAXCONCHLEN];
6586 int writeSize = 0;
6587
6588 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6589 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6590 if( pCtx->lockProxyPath!=NULL ){
6591 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6592 }else{
6593 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6594 }
6595 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006596 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006597 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6598 fsync(conchFile->h);
6599 /* If we created a new conch file (not just updated the contents of a
6600 ** valid conch file), try to match the permissions of the database
6601 */
6602 if( rc==SQLITE_OK && createConch ){
6603 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006604 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006605 if( err==0 ){
6606 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6607 S_IROTH|S_IWOTH);
6608 /* try to match the database file R/W permissions, ignore failure */
6609#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006610 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006611#else
drhff812312011-02-23 13:33:46 +00006612 do{
drhe562be52011-03-02 18:01:10 +00006613 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006614 }while( rc==(-1) && errno==EINTR );
6615 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006616 int code = errno;
6617 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6618 cmode, code, strerror(code));
6619 } else {
6620 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6621 }
6622 }else{
6623 int code = errno;
6624 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6625 err, code, strerror(code));
6626#endif
6627 }
drh715ff302008-12-03 22:32:44 +00006628 }
6629 }
drh7ed97b92010-01-20 13:07:21 +00006630 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6631
6632 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006633 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006634 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006635 int fd;
drh7ed97b92010-01-20 13:07:21 +00006636 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006637 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006638 }
6639 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006640 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006641 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006642 if( fd>=0 ){
6643 pFile->h = fd;
6644 }else{
drh9978c972010-02-23 17:36:32 +00006645 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006646 during locking */
6647 }
6648 }
6649 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6650 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6651 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6652 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6653 /* we couldn't create the proxy lock file with the old lock file path
6654 ** so try again via auto-naming
6655 */
6656 forceNewLockPath = 1;
6657 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006658 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006659 }
6660 }
6661 if( rc==SQLITE_OK ){
6662 /* Need to make a copy of path if we extracted the value
6663 ** from the conch file or the path was allocated on the stack
6664 */
6665 if( tempLockPath ){
6666 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6667 if( !pCtx->lockProxyPath ){
6668 rc = SQLITE_NOMEM;
6669 }
6670 }
6671 }
6672 if( rc==SQLITE_OK ){
6673 pCtx->conchHeld = 1;
6674
6675 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6676 afpLockingContext *afpCtx;
6677 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6678 afpCtx->dbPath = pCtx->lockProxyPath;
6679 }
6680 } else {
6681 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6682 }
drh308c2a52010-05-14 11:30:18 +00006683 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6684 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006685 return rc;
drh308c2a52010-05-14 11:30:18 +00006686 } while (1); /* in case we need to retry the :auto: lock file -
6687 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006688 }
6689}
6690
6691/*
6692** If pFile holds a lock on a conch file, then release that lock.
6693*/
6694static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006695 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006696 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6697 unixFile *conchFile; /* Name of the conch file */
6698
6699 pCtx = (proxyLockingContext *)pFile->lockingContext;
6700 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006701 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006702 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006703 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006704 if( pCtx->conchHeld>0 ){
6705 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6706 }
drh715ff302008-12-03 22:32:44 +00006707 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006708 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6709 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006710 return rc;
6711}
6712
6713/*
6714** Given the name of a database file, compute the name of its conch file.
6715** Store the conch filename in memory obtained from sqlite3_malloc().
6716** Make *pConchPath point to the new name. Return SQLITE_OK on success
6717** or SQLITE_NOMEM if unable to obtain memory.
6718**
6719** The caller is responsible for ensuring that the allocated memory
6720** space is eventually freed.
6721**
6722** *pConchPath is set to NULL if a memory allocation error occurs.
6723*/
6724static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6725 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006726 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006727 char *conchPath; /* buffer in which to construct conch name */
6728
6729 /* Allocate space for the conch filename and initialize the name to
6730 ** the name of the original database file. */
6731 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6732 if( conchPath==0 ){
6733 return SQLITE_NOMEM;
6734 }
6735 memcpy(conchPath, dbPath, len+1);
6736
6737 /* now insert a "." before the last / character */
6738 for( i=(len-1); i>=0; i-- ){
6739 if( conchPath[i]=='/' ){
6740 i++;
6741 break;
6742 }
6743 }
6744 conchPath[i]='.';
6745 while ( i<len ){
6746 conchPath[i+1]=dbPath[i];
6747 i++;
6748 }
6749
6750 /* append the "-conch" suffix to the file */
6751 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006752 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006753
6754 return SQLITE_OK;
6755}
6756
6757
6758/* Takes a fully configured proxy locking-style unix file and switches
6759** the local lock file path
6760*/
6761static int switchLockProxyPath(unixFile *pFile, const char *path) {
6762 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6763 char *oldPath = pCtx->lockProxyPath;
6764 int rc = SQLITE_OK;
6765
drh308c2a52010-05-14 11:30:18 +00006766 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006767 return SQLITE_BUSY;
6768 }
6769
6770 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6771 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6772 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6773 return SQLITE_OK;
6774 }else{
6775 unixFile *lockProxy = pCtx->lockProxy;
6776 pCtx->lockProxy=NULL;
6777 pCtx->conchHeld = 0;
6778 if( lockProxy!=NULL ){
6779 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6780 if( rc ) return rc;
6781 sqlite3_free(lockProxy);
6782 }
6783 sqlite3_free(oldPath);
6784 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6785 }
6786
6787 return rc;
6788}
6789
6790/*
6791** pFile is a file that has been opened by a prior xOpen call. dbPath
6792** is a string buffer at least MAXPATHLEN+1 characters in size.
6793**
6794** This routine find the filename associated with pFile and writes it
6795** int dbPath.
6796*/
6797static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006798#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006799 if( pFile->pMethod == &afpIoMethods ){
6800 /* afp style keeps a reference to the db path in the filePath field
6801 ** of the struct */
drhea678832008-12-10 19:26:22 +00006802 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006803 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6804 } else
drh715ff302008-12-03 22:32:44 +00006805#endif
6806 if( pFile->pMethod == &dotlockIoMethods ){
6807 /* dot lock style uses the locking context to store the dot lock
6808 ** file path */
6809 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6810 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6811 }else{
6812 /* all other styles use the locking context to store the db file path */
6813 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006814 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006815 }
6816 return SQLITE_OK;
6817}
6818
6819/*
6820** Takes an already filled in unix file and alters it so all file locking
6821** will be performed on the local proxy lock file. The following fields
6822** are preserved in the locking context so that they can be restored and
6823** the unix structure properly cleaned up at close time:
6824** ->lockingContext
6825** ->pMethod
6826*/
6827static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6828 proxyLockingContext *pCtx;
6829 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6830 char *lockPath=NULL;
6831 int rc = SQLITE_OK;
6832
drh308c2a52010-05-14 11:30:18 +00006833 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006834 return SQLITE_BUSY;
6835 }
6836 proxyGetDbPathForUnixFile(pFile, dbPath);
6837 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6838 lockPath=NULL;
6839 }else{
6840 lockPath=(char *)path;
6841 }
6842
drh308c2a52010-05-14 11:30:18 +00006843 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6844 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006845
6846 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6847 if( pCtx==0 ){
6848 return SQLITE_NOMEM;
6849 }
6850 memset(pCtx, 0, sizeof(*pCtx));
6851
6852 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6853 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006854 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6855 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6856 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6857 ** (c) the file system is read-only, then enable no-locking access.
6858 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6859 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6860 */
6861 struct statfs fsInfo;
6862 struct stat conchInfo;
6863 int goLockless = 0;
6864
drh99ab3b12011-03-02 15:09:07 +00006865 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006866 int err = errno;
6867 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6868 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6869 }
6870 }
6871 if( goLockless ){
6872 pCtx->conchHeld = -1; /* read only FS/ lockless */
6873 rc = SQLITE_OK;
6874 }
6875 }
drh715ff302008-12-03 22:32:44 +00006876 }
6877 if( rc==SQLITE_OK && lockPath ){
6878 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6879 }
6880
6881 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006882 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6883 if( pCtx->dbPath==NULL ){
6884 rc = SQLITE_NOMEM;
6885 }
6886 }
6887 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006888 /* all memory is allocated, proxys are created and assigned,
6889 ** switch the locking context and pMethod then return.
6890 */
drh715ff302008-12-03 22:32:44 +00006891 pCtx->oldLockingContext = pFile->lockingContext;
6892 pFile->lockingContext = pCtx;
6893 pCtx->pOldMethod = pFile->pMethod;
6894 pFile->pMethod = &proxyIoMethods;
6895 }else{
6896 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006897 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006898 sqlite3_free(pCtx->conchFile);
6899 }
drhd56b1212010-08-11 06:14:15 +00006900 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006901 sqlite3_free(pCtx->conchFilePath);
6902 sqlite3_free(pCtx);
6903 }
drh308c2a52010-05-14 11:30:18 +00006904 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6905 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006906 return rc;
6907}
6908
6909
6910/*
6911** This routine handles sqlite3_file_control() calls that are specific
6912** to proxy locking.
6913*/
6914static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6915 switch( op ){
6916 case SQLITE_GET_LOCKPROXYFILE: {
6917 unixFile *pFile = (unixFile*)id;
6918 if( pFile->pMethod == &proxyIoMethods ){
6919 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6920 proxyTakeConch(pFile);
6921 if( pCtx->lockProxyPath ){
6922 *(const char **)pArg = pCtx->lockProxyPath;
6923 }else{
6924 *(const char **)pArg = ":auto: (not held)";
6925 }
6926 } else {
6927 *(const char **)pArg = NULL;
6928 }
6929 return SQLITE_OK;
6930 }
6931 case SQLITE_SET_LOCKPROXYFILE: {
6932 unixFile *pFile = (unixFile*)id;
6933 int rc = SQLITE_OK;
6934 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6935 if( pArg==NULL || (const char *)pArg==0 ){
6936 if( isProxyStyle ){
6937 /* turn off proxy locking - not supported */
6938 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6939 }else{
6940 /* turn off proxy locking - already off - NOOP */
6941 rc = SQLITE_OK;
6942 }
6943 }else{
6944 const char *proxyPath = (const char *)pArg;
6945 if( isProxyStyle ){
6946 proxyLockingContext *pCtx =
6947 (proxyLockingContext*)pFile->lockingContext;
6948 if( !strcmp(pArg, ":auto:")
6949 || (pCtx->lockProxyPath &&
6950 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6951 ){
6952 rc = SQLITE_OK;
6953 }else{
6954 rc = switchLockProxyPath(pFile, proxyPath);
6955 }
6956 }else{
6957 /* turn on proxy file locking */
6958 rc = proxyTransformUnixFile(pFile, proxyPath);
6959 }
6960 }
6961 return rc;
6962 }
6963 default: {
6964 assert( 0 ); /* The call assures that only valid opcodes are sent */
6965 }
6966 }
6967 /*NOTREACHED*/
6968 return SQLITE_ERROR;
6969}
6970
6971/*
6972** Within this division (the proxying locking implementation) the procedures
6973** above this point are all utilities. The lock-related methods of the
6974** proxy-locking sqlite3_io_method object follow.
6975*/
6976
6977
6978/*
6979** This routine checks if there is a RESERVED lock held on the specified
6980** file by this or any other process. If such a lock is held, set *pResOut
6981** to a non-zero value otherwise *pResOut is set to zero. The return value
6982** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6983*/
6984static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6985 unixFile *pFile = (unixFile*)id;
6986 int rc = proxyTakeConch(pFile);
6987 if( rc==SQLITE_OK ){
6988 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006989 if( pCtx->conchHeld>0 ){
6990 unixFile *proxy = pCtx->lockProxy;
6991 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6992 }else{ /* conchHeld < 0 is lockless */
6993 pResOut=0;
6994 }
drh715ff302008-12-03 22:32:44 +00006995 }
6996 return rc;
6997}
6998
6999/*
drh308c2a52010-05-14 11:30:18 +00007000** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007001** of the following:
7002**
7003** (1) SHARED_LOCK
7004** (2) RESERVED_LOCK
7005** (3) PENDING_LOCK
7006** (4) EXCLUSIVE_LOCK
7007**
7008** Sometimes when requesting one lock state, additional lock states
7009** are inserted in between. The locking might fail on one of the later
7010** transitions leaving the lock state different from what it started but
7011** still short of its goal. The following chart shows the allowed
7012** transitions and the inserted intermediate states:
7013**
7014** UNLOCKED -> SHARED
7015** SHARED -> RESERVED
7016** SHARED -> (PENDING) -> EXCLUSIVE
7017** RESERVED -> (PENDING) -> EXCLUSIVE
7018** PENDING -> EXCLUSIVE
7019**
7020** This routine will only increase a lock. Use the sqlite3OsUnlock()
7021** routine to lower a locking level.
7022*/
drh308c2a52010-05-14 11:30:18 +00007023static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007024 unixFile *pFile = (unixFile*)id;
7025 int rc = proxyTakeConch(pFile);
7026 if( rc==SQLITE_OK ){
7027 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007028 if( pCtx->conchHeld>0 ){
7029 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007030 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7031 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007032 }else{
7033 /* conchHeld < 0 is lockless */
7034 }
drh715ff302008-12-03 22:32:44 +00007035 }
7036 return rc;
7037}
7038
7039
7040/*
drh308c2a52010-05-14 11:30:18 +00007041** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007042** must be either NO_LOCK or SHARED_LOCK.
7043**
7044** If the locking level of the file descriptor is already at or below
7045** the requested locking level, this routine is a no-op.
7046*/
drh308c2a52010-05-14 11:30:18 +00007047static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007048 unixFile *pFile = (unixFile*)id;
7049 int rc = proxyTakeConch(pFile);
7050 if( rc==SQLITE_OK ){
7051 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007052 if( pCtx->conchHeld>0 ){
7053 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007054 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7055 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007056 }else{
7057 /* conchHeld < 0 is lockless */
7058 }
drh715ff302008-12-03 22:32:44 +00007059 }
7060 return rc;
7061}
7062
7063/*
7064** Close a file that uses proxy locks.
7065*/
7066static int proxyClose(sqlite3_file *id) {
7067 if( id ){
7068 unixFile *pFile = (unixFile*)id;
7069 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7070 unixFile *lockProxy = pCtx->lockProxy;
7071 unixFile *conchFile = pCtx->conchFile;
7072 int rc = SQLITE_OK;
7073
7074 if( lockProxy ){
7075 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7076 if( rc ) return rc;
7077 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7078 if( rc ) return rc;
7079 sqlite3_free(lockProxy);
7080 pCtx->lockProxy = 0;
7081 }
7082 if( conchFile ){
7083 if( pCtx->conchHeld ){
7084 rc = proxyReleaseConch(pFile);
7085 if( rc ) return rc;
7086 }
7087 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7088 if( rc ) return rc;
7089 sqlite3_free(conchFile);
7090 }
drhd56b1212010-08-11 06:14:15 +00007091 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007092 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007093 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007094 /* restore the original locking context and pMethod then close it */
7095 pFile->lockingContext = pCtx->oldLockingContext;
7096 pFile->pMethod = pCtx->pOldMethod;
7097 sqlite3_free(pCtx);
7098 return pFile->pMethod->xClose(id);
7099 }
7100 return SQLITE_OK;
7101}
7102
7103
7104
drhd2cb50b2009-01-09 21:41:17 +00007105#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007106/*
7107** The proxy locking style is intended for use with AFP filesystems.
7108** And since AFP is only supported on MacOSX, the proxy locking is also
7109** restricted to MacOSX.
7110**
7111**
7112******************* End of the proxy lock implementation **********************
7113******************************************************************************/
7114
drh734c9862008-11-28 15:37:20 +00007115/*
danielk1977e339d652008-06-28 11:23:00 +00007116** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007117**
7118** This routine registers all VFS implementations for unix-like operating
7119** systems. This routine, and the sqlite3_os_end() routine that follows,
7120** should be the only routines in this file that are visible from other
7121** files.
drh6b9d6dd2008-12-03 19:34:47 +00007122**
7123** This routine is called once during SQLite initialization and by a
7124** single thread. The memory allocation and mutex subsystems have not
7125** necessarily been initialized when this routine is called, and so they
7126** should not be used.
drh153c62c2007-08-24 03:51:33 +00007127*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007128int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007129 /*
7130 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007131 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7132 ** to the "finder" function. (pAppData is a pointer to a pointer because
7133 ** silly C90 rules prohibit a void* from being cast to a function pointer
7134 ** and so we have to go through the intermediate pointer to avoid problems
7135 ** when compiling with -pedantic-errors on GCC.)
7136 **
7137 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007138 ** finder-function. The finder-function returns a pointer to the
7139 ** sqlite_io_methods object that implements the desired locking
7140 ** behaviors. See the division above that contains the IOMETHODS
7141 ** macro for addition information on finder-functions.
7142 **
7143 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7144 ** object. But the "autolockIoFinder" available on MacOSX does a little
7145 ** more than that; it looks at the filesystem type that hosts the
7146 ** database file and tries to choose an locking method appropriate for
7147 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007148 */
drh7708e972008-11-29 00:56:52 +00007149 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007150 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007151 sizeof(unixFile), /* szOsFile */ \
7152 MAX_PATHNAME, /* mxPathname */ \
7153 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007154 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007155 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007156 unixOpen, /* xOpen */ \
7157 unixDelete, /* xDelete */ \
7158 unixAccess, /* xAccess */ \
7159 unixFullPathname, /* xFullPathname */ \
7160 unixDlOpen, /* xDlOpen */ \
7161 unixDlError, /* xDlError */ \
7162 unixDlSym, /* xDlSym */ \
7163 unixDlClose, /* xDlClose */ \
7164 unixRandomness, /* xRandomness */ \
7165 unixSleep, /* xSleep */ \
7166 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007167 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007168 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007169 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007170 unixGetSystemCall, /* xGetSystemCall */ \
7171 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007172 }
7173
drh6b9d6dd2008-12-03 19:34:47 +00007174 /*
7175 ** All default VFSes for unix are contained in the following array.
7176 **
7177 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7178 ** by the SQLite core when the VFS is registered. So the following
7179 ** array cannot be const.
7180 */
danielk1977e339d652008-06-28 11:23:00 +00007181 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007182#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007183 UNIXVFS("unix", autolockIoFinder ),
7184#else
7185 UNIXVFS("unix", posixIoFinder ),
7186#endif
7187 UNIXVFS("unix-none", nolockIoFinder ),
7188 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007189 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007190#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007191 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007192#endif
7193#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007194 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007195#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007196 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007197#endif
chw78a13182009-04-07 05:35:03 +00007198#endif
drhd2cb50b2009-01-09 21:41:17 +00007199#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007200 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007201 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007202 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007203#endif
drh153c62c2007-08-24 03:51:33 +00007204 };
drh6b9d6dd2008-12-03 19:34:47 +00007205 unsigned int i; /* Loop counter */
7206
drh2aa5a002011-04-13 13:42:25 +00007207 /* Double-check that the aSyscall[] array has been constructed
7208 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007209 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007210
drh6b9d6dd2008-12-03 19:34:47 +00007211 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007212 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007213 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007214 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007215 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007216}
danielk1977e339d652008-06-28 11:23:00 +00007217
7218/*
drh6b9d6dd2008-12-03 19:34:47 +00007219** Shutdown the operating system interface.
7220**
7221** Some operating systems might need to do some cleanup in this routine,
7222** to release dynamically allocated objects. But not on unix.
7223** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007224*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007225int sqlite3_os_end(void){
7226 return SQLITE_OK;
7227}
drhdce8bdb2007-08-16 13:01:44 +00007228
danielk197729bafea2008-06-26 10:41:19 +00007229#endif /* SQLITE_OS_UNIX */