blob: 88f3177021bc7ad76587db40eb760b913a721ae4 [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 */
dan6101d502013-03-22 08:58:38 +0000252 sqlite3_int64 mmapSize; /* Size of xMremap() */
253 void *pMapRegion; /* Area memory mapped */
drh8f941bc2009-01-14 23:03:40 +0000254#endif
danielk1977967a4a12007-08-20 14:23:44 +0000255#ifdef SQLITE_TEST
256 /* In test mode, increase the size of this structure a bit so that
257 ** it is larger than the struct CrashFile defined in test6.c.
258 */
259 char aPadding[32];
260#endif
drh9cbe6352005-11-29 03:13:21 +0000261};
262
drh0ccebe72005-06-07 22:22:50 +0000263/*
drha7e61d82011-03-12 17:02:57 +0000264** Allowed values for the unixFile.ctrlFlags bitmask:
265*/
drhf0b190d2011-07-26 16:03:07 +0000266#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
267#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
268#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000269#ifndef SQLITE_DISABLE_DIRSYNC
270# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
271#else
272# define UNIXFILE_DIRSYNC 0x00
273#endif
drhcb15f352011-12-23 01:04:17 +0000274#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000275#define UNIXFILE_DELETE 0x20 /* Delete on close */
276#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
277#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000278
279/*
drh198bf392006-01-06 21:52:49 +0000280** Include code that is common to all os_*.c files
281*/
282#include "os_common.h"
283
284/*
drh0ccebe72005-06-07 22:22:50 +0000285** Define various macros that are missing from some systems.
286*/
drhbbd42a62004-05-22 17:41:58 +0000287#ifndef O_LARGEFILE
288# define O_LARGEFILE 0
289#endif
290#ifdef SQLITE_DISABLE_LFS
291# undef O_LARGEFILE
292# define O_LARGEFILE 0
293#endif
294#ifndef O_NOFOLLOW
295# define O_NOFOLLOW 0
296#endif
297#ifndef O_BINARY
298# define O_BINARY 0
299#endif
300
301/*
drh2b4b5962005-06-15 17:47:55 +0000302** The threadid macro resolves to the thread-id or to 0. Used for
303** testing and debugging only.
304*/
drhd677b3d2007-08-20 22:48:41 +0000305#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000306#define threadid pthread_self()
307#else
308#define threadid 0
309#endif
310
drh99ab3b12011-03-02 15:09:07 +0000311/*
drh9a3baf12011-04-25 18:01:27 +0000312** Different Unix systems declare open() in different ways. Same use
313** open(const char*,int,mode_t). Others use open(const char*,int,...).
314** The difference is important when using a pointer to the function.
315**
316** The safest way to deal with the problem is to always use this wrapper
317** which always has the same well-defined interface.
318*/
319static int posixOpen(const char *zFile, int flags, int mode){
320 return open(zFile, flags, mode);
321}
322
drhed466822012-05-31 13:10:49 +0000323/*
324** On some systems, calls to fchown() will trigger a message in a security
325** log if they come from non-root processes. So avoid calling fchown() if
326** we are not running as root.
327*/
328static int posixFchown(int fd, uid_t uid, gid_t gid){
329 return geteuid() ? 0 : fchown(fd,uid,gid);
330}
331
drh90315a22011-08-10 01:52:12 +0000332/* Forward reference */
333static int openDirectory(const char*, int*);
334
drh9a3baf12011-04-25 18:01:27 +0000335/*
drh99ab3b12011-03-02 15:09:07 +0000336** Many system calls are accessed through pointer-to-functions so that
337** they may be overridden at runtime to facilitate fault injection during
338** testing and sandboxing. The following array holds the names and pointers
339** to all overrideable system calls.
340*/
341static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000342 const char *zName; /* Name of the sytem call */
343 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
344 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000345} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000346 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
347#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000348
drh58ad5802011-03-23 22:02:23 +0000349 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000350#define osClose ((int(*)(int))aSyscall[1].pCurrent)
351
drh58ad5802011-03-23 22:02:23 +0000352 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000353#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
354
drh58ad5802011-03-23 22:02:23 +0000355 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000356#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
357
drh58ad5802011-03-23 22:02:23 +0000358 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000359#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
360
361/*
362** The DJGPP compiler environment looks mostly like Unix, but it
363** lacks the fcntl() system call. So redefine fcntl() to be something
364** that always succeeds. This means that locking does not occur under
365** DJGPP. But it is DOS - what did you expect?
366*/
367#ifdef __DJGPP__
368 { "fstat", 0, 0 },
369#define osFstat(a,b,c) 0
370#else
drh58ad5802011-03-23 22:02:23 +0000371 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000372#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
373#endif
374
drh58ad5802011-03-23 22:02:23 +0000375 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000376#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
377
drh58ad5802011-03-23 22:02:23 +0000378 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000379#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000380
drh58ad5802011-03-23 22:02:23 +0000381 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000382#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
383
drhd4a80312011-04-15 14:33:20 +0000384#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000385 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000386#else
drh58ad5802011-03-23 22:02:23 +0000387 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000388#endif
389#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
390
391#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000392 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000393#else
drh58ad5802011-03-23 22:02:23 +0000394 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000395#endif
396#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
397
drh58ad5802011-03-23 22:02:23 +0000398 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000399#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
400
drhd4a80312011-04-15 14:33:20 +0000401#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000402 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000403#else
drh58ad5802011-03-23 22:02:23 +0000404 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000405#endif
406#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
407 aSyscall[12].pCurrent)
408
409#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000410 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000411#else
drh58ad5802011-03-23 22:02:23 +0000412 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000413#endif
414#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
415 aSyscall[13].pCurrent)
416
drh58ad5802011-03-23 22:02:23 +0000417 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000418#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000419
420#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000421 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000422#else
drh58ad5802011-03-23 22:02:23 +0000423 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000424#endif
dan0fd7d862011-03-29 10:04:23 +0000425#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000426
drh036ac7f2011-08-08 23:18:05 +0000427 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
428#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
429
drh90315a22011-08-10 01:52:12 +0000430 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
431#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
432
drh9ef6bc42011-11-04 02:24:02 +0000433 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
434#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
435
436 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
437#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
438
drhed466822012-05-31 13:10:49 +0000439 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000440#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000441
drhe562be52011-03-02 18:01:10 +0000442}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000443
444/*
445** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000446** "unix" VFSes. Return SQLITE_OK opon successfully updating the
447** system call pointer, or SQLITE_NOTFOUND if there is no configurable
448** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000449*/
450static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000451 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
452 const char *zName, /* Name of system call to override */
453 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000454){
drh58ad5802011-03-23 22:02:23 +0000455 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000456 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000457
458 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000459 if( zName==0 ){
460 /* If no zName is given, restore all system calls to their default
461 ** settings and return NULL
462 */
dan51438a72011-04-02 17:00:47 +0000463 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000464 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
465 if( aSyscall[i].pDefault ){
466 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000467 }
468 }
469 }else{
470 /* If zName is specified, operate on only the one system call
471 ** specified.
472 */
473 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
474 if( strcmp(zName, aSyscall[i].zName)==0 ){
475 if( aSyscall[i].pDefault==0 ){
476 aSyscall[i].pDefault = aSyscall[i].pCurrent;
477 }
drh1df30962011-03-02 19:06:42 +0000478 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000479 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
480 aSyscall[i].pCurrent = pNewFunc;
481 break;
482 }
483 }
484 }
485 return rc;
486}
487
drh1df30962011-03-02 19:06:42 +0000488/*
489** Return the value of a system call. Return NULL if zName is not a
490** recognized system call name. NULL is also returned if the system call
491** is currently undefined.
492*/
drh58ad5802011-03-23 22:02:23 +0000493static sqlite3_syscall_ptr unixGetSystemCall(
494 sqlite3_vfs *pNotUsed,
495 const char *zName
496){
497 unsigned int i;
498
499 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000500 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
501 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
502 }
503 return 0;
504}
505
506/*
507** Return the name of the first system call after zName. If zName==NULL
508** then return the name of the first system call. Return NULL if zName
509** is the last system call or if zName is not the name of a valid
510** system call.
511*/
512static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000513 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000514
515 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000516 if( zName ){
517 for(i=0; i<ArraySize(aSyscall)-1; i++){
518 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000519 }
520 }
dan0fd7d862011-03-29 10:04:23 +0000521 for(i++; i<ArraySize(aSyscall); i++){
522 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000523 }
524 return 0;
525}
526
drhad4f1e52011-03-04 15:43:57 +0000527/*
drh8c815d12012-02-13 20:16:37 +0000528** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000529** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000530**
531** If the file creation mode "m" is 0 then set it to the default for
532** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
533** 0644) as modified by the system umask. If m is not 0, then
534** make the file creation mode be exactly m ignoring the umask.
535**
536** The m parameter will be non-zero only when creating -wal, -journal,
537** and -shm files. We want those files to have *exactly* the same
538** permissions as their original database, unadulterated by the umask.
539** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
540** transaction crashes and leaves behind hot journals, then any
541** process that is able to write to the database will also be able to
542** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000543*/
drh8c815d12012-02-13 20:16:37 +0000544static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000545 int fd;
drhe1186ab2013-01-04 20:45:13 +0000546 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5adc60b2012-04-14 13:25:11 +0000547 do{
548#if defined(O_CLOEXEC)
549 fd = osOpen(z,f|O_CLOEXEC,m2);
550#else
551 fd = osOpen(z,f,m2);
552#endif
553 }while( fd<0 && errno==EINTR );
drhe1186ab2013-01-04 20:45:13 +0000554 if( fd>=0 ){
555 if( m!=0 ){
556 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000557 if( osFstat(fd, &statbuf)==0
558 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000559 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000560 ){
drhe1186ab2013-01-04 20:45:13 +0000561 osFchmod(fd, m);
562 }
563 }
drh5adc60b2012-04-14 13:25:11 +0000564#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000565 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000566#endif
drhe1186ab2013-01-04 20:45:13 +0000567 }
drh5adc60b2012-04-14 13:25:11 +0000568 return fd;
drhad4f1e52011-03-04 15:43:57 +0000569}
danielk197713adf8a2004-06-03 16:08:41 +0000570
drh107886a2008-11-21 22:21:50 +0000571/*
dan9359c7b2009-08-21 08:29:10 +0000572** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000573** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000574** vxworksFileId objects used by this file, all of which may be
575** shared by multiple threads.
576**
577** Function unixMutexHeld() is used to assert() that the global mutex
578** is held when required. This function is only used as part of assert()
579** statements. e.g.
580**
581** unixEnterMutex()
582** assert( unixMutexHeld() );
583** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000584*/
585static void unixEnterMutex(void){
586 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
587}
588static void unixLeaveMutex(void){
589 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
590}
dan9359c7b2009-08-21 08:29:10 +0000591#ifdef SQLITE_DEBUG
592static int unixMutexHeld(void) {
593 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
594}
595#endif
drh107886a2008-11-21 22:21:50 +0000596
drh734c9862008-11-28 15:37:20 +0000597
drh30ddce62011-10-15 00:16:30 +0000598#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000599/*
600** Helper function for printing out trace information from debugging
601** binaries. This returns the string represetation of the supplied
602** integer lock-type.
603*/
drh308c2a52010-05-14 11:30:18 +0000604static const char *azFileLock(int eFileLock){
605 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000606 case NO_LOCK: return "NONE";
607 case SHARED_LOCK: return "SHARED";
608 case RESERVED_LOCK: return "RESERVED";
609 case PENDING_LOCK: return "PENDING";
610 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000611 }
612 return "ERROR";
613}
614#endif
615
616#ifdef SQLITE_LOCK_TRACE
617/*
618** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000619**
drh734c9862008-11-28 15:37:20 +0000620** This routine is used for troubleshooting locks on multithreaded
621** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
622** command-line option on the compiler. This code is normally
623** turned off.
624*/
625static int lockTrace(int fd, int op, struct flock *p){
626 char *zOpName, *zType;
627 int s;
628 int savedErrno;
629 if( op==F_GETLK ){
630 zOpName = "GETLK";
631 }else if( op==F_SETLK ){
632 zOpName = "SETLK";
633 }else{
drh99ab3b12011-03-02 15:09:07 +0000634 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000635 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
636 return s;
637 }
638 if( p->l_type==F_RDLCK ){
639 zType = "RDLCK";
640 }else if( p->l_type==F_WRLCK ){
641 zType = "WRLCK";
642 }else if( p->l_type==F_UNLCK ){
643 zType = "UNLCK";
644 }else{
645 assert( 0 );
646 }
647 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000648 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000649 savedErrno = errno;
650 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
651 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
652 (int)p->l_pid, s);
653 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
654 struct flock l2;
655 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000656 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000657 if( l2.l_type==F_RDLCK ){
658 zType = "RDLCK";
659 }else if( l2.l_type==F_WRLCK ){
660 zType = "WRLCK";
661 }else if( l2.l_type==F_UNLCK ){
662 zType = "UNLCK";
663 }else{
664 assert( 0 );
665 }
666 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
667 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
668 }
669 errno = savedErrno;
670 return s;
671}
drh99ab3b12011-03-02 15:09:07 +0000672#undef osFcntl
673#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000674#endif /* SQLITE_LOCK_TRACE */
675
drhff812312011-02-23 13:33:46 +0000676/*
677** Retry ftruncate() calls that fail due to EINTR
678*/
drhff812312011-02-23 13:33:46 +0000679static int robust_ftruncate(int h, sqlite3_int64 sz){
680 int rc;
drh99ab3b12011-03-02 15:09:07 +0000681 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000682 return rc;
683}
drh734c9862008-11-28 15:37:20 +0000684
685/*
686** This routine translates a standard POSIX errno code into something
687** useful to the clients of the sqlite3 functions. Specifically, it is
688** intended to translate a variety of "try again" errors into SQLITE_BUSY
689** and a variety of "please close the file descriptor NOW" errors into
690** SQLITE_IOERR
691**
692** Errors during initialization of locks, or file system support for locks,
693** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
694*/
695static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
696 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000697#if 0
698 /* At one point this code was not commented out. In theory, this branch
699 ** should never be hit, as this function should only be called after
700 ** a locking-related function (i.e. fcntl()) has returned non-zero with
701 ** the value of errno as the first argument. Since a system call has failed,
702 ** errno should be non-zero.
703 **
704 ** Despite this, if errno really is zero, we still don't want to return
705 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
706 ** propagated back to the caller. Commenting this branch out means errno==0
707 ** will be handled by the "default:" case below.
708 */
drh734c9862008-11-28 15:37:20 +0000709 case 0:
710 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000711#endif
712
drh734c9862008-11-28 15:37:20 +0000713 case EAGAIN:
714 case ETIMEDOUT:
715 case EBUSY:
716 case EINTR:
717 case ENOLCK:
718 /* random NFS retry error, unless during file system support
719 * introspection, in which it actually means what it says */
720 return SQLITE_BUSY;
721
722 case EACCES:
723 /* EACCES is like EAGAIN during locking operations, but not any other time*/
724 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000725 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
726 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
727 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000728 return SQLITE_BUSY;
729 }
730 /* else fall through */
731 case EPERM:
732 return SQLITE_PERM;
733
danea83bc62011-04-01 11:56:32 +0000734 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
735 ** this module never makes such a call. And the code in SQLite itself
736 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
737 ** this case is also commented out. If the system does set errno to EDEADLK,
738 ** the default SQLITE_IOERR_XXX code will be returned. */
739#if 0
drh734c9862008-11-28 15:37:20 +0000740 case EDEADLK:
741 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000742#endif
drh734c9862008-11-28 15:37:20 +0000743
744#if EOPNOTSUPP!=ENOTSUP
745 case EOPNOTSUPP:
746 /* something went terribly awry, unless during file system support
747 * introspection, in which it actually means what it says */
748#endif
749#ifdef ENOTSUP
750 case ENOTSUP:
751 /* invalid fd, unless during file system support introspection, in which
752 * it actually means what it says */
753#endif
754 case EIO:
755 case EBADF:
756 case EINVAL:
757 case ENOTCONN:
758 case ENODEV:
759 case ENXIO:
760 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000761#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000762 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000763#endif
drh734c9862008-11-28 15:37:20 +0000764 case ENOSYS:
765 /* these should force the client to close the file and reconnect */
766
767 default:
768 return sqliteIOErr;
769 }
770}
771
772
773
774/******************************************************************************
775****************** Begin Unique File ID Utility Used By VxWorks ***************
776**
777** On most versions of unix, we can get a unique ID for a file by concatenating
778** the device number and the inode number. But this does not work on VxWorks.
779** On VxWorks, a unique file id must be based on the canonical filename.
780**
781** A pointer to an instance of the following structure can be used as a
782** unique file ID in VxWorks. Each instance of this structure contains
783** a copy of the canonical filename. There is also a reference count.
784** The structure is reclaimed when the number of pointers to it drops to
785** zero.
786**
787** There are never very many files open at one time and lookups are not
788** a performance-critical path, so it is sufficient to put these
789** structures on a linked list.
790*/
791struct vxworksFileId {
792 struct vxworksFileId *pNext; /* Next in a list of them all */
793 int nRef; /* Number of references to this one */
794 int nName; /* Length of the zCanonicalName[] string */
795 char *zCanonicalName; /* Canonical filename */
796};
797
798#if OS_VXWORKS
799/*
drh9b35ea62008-11-29 02:20:26 +0000800** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000801** variable:
802*/
803static struct vxworksFileId *vxworksFileList = 0;
804
805/*
806** Simplify a filename into its canonical form
807** by making the following changes:
808**
809** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000810** * convert /./ into just /
811** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000812**
813** Changes are made in-place. Return the new name length.
814**
815** The original filename is in z[0..n-1]. Return the number of
816** characters in the simplified name.
817*/
818static int vxworksSimplifyName(char *z, int n){
819 int i, j;
820 while( n>1 && z[n-1]=='/' ){ n--; }
821 for(i=j=0; i<n; i++){
822 if( z[i]=='/' ){
823 if( z[i+1]=='/' ) continue;
824 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
825 i += 1;
826 continue;
827 }
828 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
829 while( j>0 && z[j-1]!='/' ){ j--; }
830 if( j>0 ){ j--; }
831 i += 2;
832 continue;
833 }
834 }
835 z[j++] = z[i];
836 }
837 z[j] = 0;
838 return j;
839}
840
841/*
842** Find a unique file ID for the given absolute pathname. Return
843** a pointer to the vxworksFileId object. This pointer is the unique
844** file ID.
845**
846** The nRef field of the vxworksFileId object is incremented before
847** the object is returned. A new vxworksFileId object is created
848** and added to the global list if necessary.
849**
850** If a memory allocation error occurs, return NULL.
851*/
852static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
853 struct vxworksFileId *pNew; /* search key and new file ID */
854 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
855 int n; /* Length of zAbsoluteName string */
856
857 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000858 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000859 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
860 if( pNew==0 ) return 0;
861 pNew->zCanonicalName = (char*)&pNew[1];
862 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
863 n = vxworksSimplifyName(pNew->zCanonicalName, n);
864
865 /* Search for an existing entry that matching the canonical name.
866 ** If found, increment the reference count and return a pointer to
867 ** the existing file ID.
868 */
869 unixEnterMutex();
870 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
871 if( pCandidate->nName==n
872 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
873 ){
874 sqlite3_free(pNew);
875 pCandidate->nRef++;
876 unixLeaveMutex();
877 return pCandidate;
878 }
879 }
880
881 /* No match was found. We will make a new file ID */
882 pNew->nRef = 1;
883 pNew->nName = n;
884 pNew->pNext = vxworksFileList;
885 vxworksFileList = pNew;
886 unixLeaveMutex();
887 return pNew;
888}
889
890/*
891** Decrement the reference count on a vxworksFileId object. Free
892** the object when the reference count reaches zero.
893*/
894static void vxworksReleaseFileId(struct vxworksFileId *pId){
895 unixEnterMutex();
896 assert( pId->nRef>0 );
897 pId->nRef--;
898 if( pId->nRef==0 ){
899 struct vxworksFileId **pp;
900 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
901 assert( *pp==pId );
902 *pp = pId->pNext;
903 sqlite3_free(pId);
904 }
905 unixLeaveMutex();
906}
907#endif /* OS_VXWORKS */
908/*************** End of Unique File ID Utility Used By VxWorks ****************
909******************************************************************************/
910
911
912/******************************************************************************
913*************************** Posix Advisory Locking ****************************
914**
drh9b35ea62008-11-29 02:20:26 +0000915** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000916** section 6.5.2.2 lines 483 through 490 specify that when a process
917** sets or clears a lock, that operation overrides any prior locks set
918** by the same process. It does not explicitly say so, but this implies
919** that it overrides locks set by the same process using a different
920** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000921**
922** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000923** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
924**
925** Suppose ./file1 and ./file2 are really the same file (because
926** one is a hard or symbolic link to the other) then if you set
927** an exclusive lock on fd1, then try to get an exclusive lock
928** on fd2, it works. I would have expected the second lock to
929** fail since there was already a lock on the file due to fd1.
930** But not so. Since both locks came from the same process, the
931** second overrides the first, even though they were on different
932** file descriptors opened on different file names.
933**
drh734c9862008-11-28 15:37:20 +0000934** This means that we cannot use POSIX locks to synchronize file access
935** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000936** to synchronize access for threads in separate processes, but not
937** threads within the same process.
938**
939** To work around the problem, SQLite has to manage file locks internally
940** on its own. Whenever a new database is opened, we have to find the
941** specific inode of the database file (the inode is determined by the
942** st_dev and st_ino fields of the stat structure that fstat() fills in)
943** and check for locks already existing on that inode. When locks are
944** created or removed, we have to look at our own internal record of the
945** locks to see if another thread has previously set a lock on that same
946** inode.
947**
drh9b35ea62008-11-29 02:20:26 +0000948** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
949** For VxWorks, we have to use the alternative unique ID system based on
950** canonical filename and implemented in the previous division.)
951**
danielk1977ad94b582007-08-20 06:44:22 +0000952** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000953** descriptor. It is now a structure that holds the integer file
954** descriptor and a pointer to a structure that describes the internal
955** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000956** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000957** point to the same locking structure. The locking structure keeps
958** a reference count (so we will know when to delete it) and a "cnt"
959** field that tells us its internal lock status. cnt==0 means the
960** file is unlocked. cnt==-1 means the file has an exclusive lock.
961** cnt>0 means there are cnt shared locks on the file.
962**
963** Any attempt to lock or unlock a file first checks the locking
964** structure. The fcntl() system call is only invoked to set a
965** POSIX lock if the internal lock structure transitions between
966** a locked and an unlocked state.
967**
drh734c9862008-11-28 15:37:20 +0000968** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000969**
970** If you close a file descriptor that points to a file that has locks,
971** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000972** released. To work around this problem, each unixInodeInfo object
973** maintains a count of the number of pending locks on tha inode.
974** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000975** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000976** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000977** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000978** be closed and that list is walked (and cleared) when the last lock
979** clears.
980**
drh9b35ea62008-11-29 02:20:26 +0000981** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000982**
drh9b35ea62008-11-29 02:20:26 +0000983** Many older versions of linux use the LinuxThreads library which is
984** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000985** A cannot be modified or overridden by a different thread B.
986** Only thread A can modify the lock. Locking behavior is correct
987** if the appliation uses the newer Native Posix Thread Library (NPTL)
988** on linux - with NPTL a lock created by thread A can override locks
989** in thread B. But there is no way to know at compile-time which
990** threading library is being used. So there is no way to know at
991** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000992** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000993** current process.
drh5fdae772004-06-29 03:29:00 +0000994**
drh8af6c222010-05-14 12:43:01 +0000995** SQLite used to support LinuxThreads. But support for LinuxThreads
996** was dropped beginning with version 3.7.0. SQLite will still work with
997** LinuxThreads provided that (1) there is no more than one connection
998** per database file in the same process and (2) database connections
999** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001000*/
1001
1002/*
1003** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001004** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001005*/
1006struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001007 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001008#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001009 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001010#else
drh107886a2008-11-21 22:21:50 +00001011 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001012#endif
1013};
1014
1015/*
drhbbd42a62004-05-22 17:41:58 +00001016** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001017** inode. Or, on LinuxThreads, there is one of these structures for
1018** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001019**
danielk1977ad94b582007-08-20 06:44:22 +00001020** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001021** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001022** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001023*/
drh8af6c222010-05-14 12:43:01 +00001024struct unixInodeInfo {
1025 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001026 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001027 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1028 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001029 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001030 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1031 int nLock; /* Number of outstanding file locks */
1032 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1033 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1034 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001035#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001036 unsigned long long sharedByte; /* for AFP simulated shared lock */
1037#endif
drh6c7d5c52008-11-21 20:32:33 +00001038#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001039 sem_t *pSem; /* Named POSIX semaphore */
1040 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001041#endif
drhbbd42a62004-05-22 17:41:58 +00001042};
1043
drhda0e7682008-07-30 15:27:54 +00001044/*
drh8af6c222010-05-14 12:43:01 +00001045** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001046*/
drhd91c68f2010-05-14 14:52:25 +00001047static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001048
drh5fdae772004-06-29 03:29:00 +00001049/*
dane18d4952011-02-21 11:46:24 +00001050**
1051** This function - unixLogError_x(), is only ever called via the macro
1052** unixLogError().
1053**
1054** It is invoked after an error occurs in an OS function and errno has been
1055** set. It logs a message using sqlite3_log() containing the current value of
1056** errno and, if possible, the human-readable equivalent from strerror() or
1057** strerror_r().
1058**
1059** The first argument passed to the macro should be the error code that
1060** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1061** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001062** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001063** if any.
1064*/
drh0e9365c2011-03-02 02:08:13 +00001065#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1066static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001067 int errcode, /* SQLite error code */
1068 const char *zFunc, /* Name of OS function that failed */
1069 const char *zPath, /* File path associated with error */
1070 int iLine /* Source line number where error occurred */
1071){
1072 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001073 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001074
1075 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1076 ** the strerror() function to obtain the human-readable error message
1077 ** equivalent to errno. Otherwise, use strerror_r().
1078 */
1079#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1080 char aErr[80];
1081 memset(aErr, 0, sizeof(aErr));
1082 zErr = aErr;
1083
1084 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001085 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001086 ** returns a pointer to a buffer containing the error message. That pointer
1087 ** may point to aErr[], or it may point to some static storage somewhere.
1088 ** Otherwise, assume that the system provides the POSIX version of
1089 ** strerror_r(), which always writes an error message into aErr[].
1090 **
1091 ** If the code incorrectly assumes that it is the POSIX version that is
1092 ** available, the error message will often be an empty string. Not a
1093 ** huge problem. Incorrectly concluding that the GNU version is available
1094 ** could lead to a segfault though.
1095 */
1096#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1097 zErr =
1098# endif
drh0e9365c2011-03-02 02:08:13 +00001099 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001100
1101#elif SQLITE_THREADSAFE
1102 /* This is a threadsafe build, but strerror_r() is not available. */
1103 zErr = "";
1104#else
1105 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001106 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001107#endif
1108
1109 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001110 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001111 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001112 "os_unix.c:%d: (%d) %s(%s) - %s",
1113 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001114 );
1115
1116 return errcode;
1117}
1118
drh0e9365c2011-03-02 02:08:13 +00001119/*
1120** Close a file descriptor.
1121**
1122** We assume that close() almost always works, since it is only in a
1123** very sick application or on a very sick platform that it might fail.
1124** If it does fail, simply leak the file descriptor, but do log the
1125** error.
1126**
1127** Note that it is not safe to retry close() after EINTR since the
1128** file descriptor might have already been reused by another thread.
1129** So we don't even try to recover from an EINTR. Just log the error
1130** and move on.
1131*/
1132static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001133 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001134 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1135 pFile ? pFile->zPath : 0, lineno);
1136 }
1137}
dane18d4952011-02-21 11:46:24 +00001138
1139/*
danb0ac3e32010-06-16 10:55:42 +00001140** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001141*/
drh0e9365c2011-03-02 02:08:13 +00001142static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001143 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001144 UnixUnusedFd *p;
1145 UnixUnusedFd *pNext;
1146 for(p=pInode->pUnused; p; p=pNext){
1147 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001148 robust_close(pFile, p->fd, __LINE__);
1149 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001150 }
drh0e9365c2011-03-02 02:08:13 +00001151 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001152}
1153
1154/*
drh8af6c222010-05-14 12:43:01 +00001155** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001156**
1157** The mutex entered using the unixEnterMutex() function must be held
1158** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001159*/
danb0ac3e32010-06-16 10:55:42 +00001160static void releaseInodeInfo(unixFile *pFile){
1161 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001162 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001163 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001164 pInode->nRef--;
1165 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001166 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001167 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001168 if( pInode->pPrev ){
1169 assert( pInode->pPrev->pNext==pInode );
1170 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001171 }else{
drh8af6c222010-05-14 12:43:01 +00001172 assert( inodeList==pInode );
1173 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001174 }
drh8af6c222010-05-14 12:43:01 +00001175 if( pInode->pNext ){
1176 assert( pInode->pNext->pPrev==pInode );
1177 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001178 }
drh8af6c222010-05-14 12:43:01 +00001179 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001180 }
drhbbd42a62004-05-22 17:41:58 +00001181 }
1182}
1183
1184/*
drh8af6c222010-05-14 12:43:01 +00001185** Given a file descriptor, locate the unixInodeInfo object that
1186** describes that file descriptor. Create a new one if necessary. The
1187** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001188**
dan9359c7b2009-08-21 08:29:10 +00001189** The mutex entered using the unixEnterMutex() function must be held
1190** when this function is called.
1191**
drh6c7d5c52008-11-21 20:32:33 +00001192** Return an appropriate error code.
1193*/
drh8af6c222010-05-14 12:43:01 +00001194static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001195 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001196 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001197){
1198 int rc; /* System call return code */
1199 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001200 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1201 struct stat statbuf; /* Low-level file information */
1202 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001203
dan9359c7b2009-08-21 08:29:10 +00001204 assert( unixMutexHeld() );
1205
drh6c7d5c52008-11-21 20:32:33 +00001206 /* Get low-level information about the file that we can used to
1207 ** create a unique name for the file.
1208 */
1209 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001210 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001211 if( rc!=0 ){
1212 pFile->lastErrno = errno;
1213#ifdef EOVERFLOW
1214 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1215#endif
1216 return SQLITE_IOERR;
1217 }
1218
drheb0d74f2009-02-03 15:27:02 +00001219#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001220 /* On OS X on an msdos filesystem, the inode number is reported
1221 ** incorrectly for zero-size files. See ticket #3260. To work
1222 ** around this problem (we consider it a bug in OS X, not SQLite)
1223 ** we always increase the file size to 1 by writing a single byte
1224 ** prior to accessing the inode number. The one byte written is
1225 ** an ASCII 'S' character which also happens to be the first byte
1226 ** in the header of every SQLite database. In this way, if there
1227 ** is a race condition such that another thread has already populated
1228 ** the first page of the database, no damage is done.
1229 */
drh7ed97b92010-01-20 13:07:21 +00001230 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001231 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001232 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001233 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001234 return SQLITE_IOERR;
1235 }
drh99ab3b12011-03-02 15:09:07 +00001236 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001237 if( rc!=0 ){
1238 pFile->lastErrno = errno;
1239 return SQLITE_IOERR;
1240 }
1241 }
drheb0d74f2009-02-03 15:27:02 +00001242#endif
drh6c7d5c52008-11-21 20:32:33 +00001243
drh8af6c222010-05-14 12:43:01 +00001244 memset(&fileId, 0, sizeof(fileId));
1245 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001246#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001247 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001248#else
drh8af6c222010-05-14 12:43:01 +00001249 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001250#endif
drh8af6c222010-05-14 12:43:01 +00001251 pInode = inodeList;
1252 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1253 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001254 }
drh8af6c222010-05-14 12:43:01 +00001255 if( pInode==0 ){
1256 pInode = sqlite3_malloc( sizeof(*pInode) );
1257 if( pInode==0 ){
1258 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001259 }
drh8af6c222010-05-14 12:43:01 +00001260 memset(pInode, 0, sizeof(*pInode));
1261 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1262 pInode->nRef = 1;
1263 pInode->pNext = inodeList;
1264 pInode->pPrev = 0;
1265 if( inodeList ) inodeList->pPrev = pInode;
1266 inodeList = pInode;
1267 }else{
1268 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001269 }
drh8af6c222010-05-14 12:43:01 +00001270 *ppInode = pInode;
1271 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001272}
drh6c7d5c52008-11-21 20:32:33 +00001273
aswift5b1a2562008-08-22 00:22:35 +00001274
1275/*
danielk197713adf8a2004-06-03 16:08:41 +00001276** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001277** file by this or any other process. If such a lock is held, set *pResOut
1278** to a non-zero value otherwise *pResOut is set to zero. The return value
1279** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001280*/
danielk1977861f7452008-06-05 11:39:11 +00001281static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001282 int rc = SQLITE_OK;
1283 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001284 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001285
danielk1977861f7452008-06-05 11:39:11 +00001286 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1287
drh054889e2005-11-30 03:20:31 +00001288 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001289 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001290
1291 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001292 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001293 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001294 }
1295
drh2ac3ee92004-06-07 16:27:46 +00001296 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001297 */
danielk197709480a92009-02-09 05:32:32 +00001298#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001299 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001300 struct flock lock;
1301 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001302 lock.l_start = RESERVED_BYTE;
1303 lock.l_len = 1;
1304 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001305 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1306 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1307 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001308 } else if( lock.l_type!=F_UNLCK ){
1309 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001310 }
1311 }
danielk197709480a92009-02-09 05:32:32 +00001312#endif
danielk197713adf8a2004-06-03 16:08:41 +00001313
drh6c7d5c52008-11-21 20:32:33 +00001314 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001315 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001316
aswift5b1a2562008-08-22 00:22:35 +00001317 *pResOut = reserved;
1318 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001319}
1320
1321/*
drha7e61d82011-03-12 17:02:57 +00001322** Attempt to set a system-lock on the file pFile. The lock is
1323** described by pLock.
1324**
drh77197112011-03-15 19:08:48 +00001325** If the pFile was opened read/write from unix-excl, then the only lock
1326** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001327** the first time any lock is attempted. All subsequent system locking
1328** operations become no-ops. Locking operations still happen internally,
1329** in order to coordinate access between separate database connections
1330** within this process, but all of that is handled in memory and the
1331** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001332**
1333** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1334** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1335** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001336**
1337** Zero is returned if the call completes successfully, or -1 if a call
1338** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001339*/
1340static int unixFileLock(unixFile *pFile, struct flock *pLock){
1341 int rc;
drh3cb93392011-03-12 18:10:44 +00001342 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001343 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001344 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001345 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1346 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1347 ){
drh3cb93392011-03-12 18:10:44 +00001348 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001349 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001350 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001351 lock.l_whence = SEEK_SET;
1352 lock.l_start = SHARED_FIRST;
1353 lock.l_len = SHARED_SIZE;
1354 lock.l_type = F_WRLCK;
1355 rc = osFcntl(pFile->h, F_SETLK, &lock);
1356 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001357 pInode->bProcessLock = 1;
1358 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001359 }else{
1360 rc = 0;
1361 }
1362 }else{
1363 rc = osFcntl(pFile->h, F_SETLK, pLock);
1364 }
1365 return rc;
1366}
1367
1368/*
drh308c2a52010-05-14 11:30:18 +00001369** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001370** of the following:
1371**
drh2ac3ee92004-06-07 16:27:46 +00001372** (1) SHARED_LOCK
1373** (2) RESERVED_LOCK
1374** (3) PENDING_LOCK
1375** (4) EXCLUSIVE_LOCK
1376**
drhb3e04342004-06-08 00:47:47 +00001377** Sometimes when requesting one lock state, additional lock states
1378** are inserted in between. The locking might fail on one of the later
1379** transitions leaving the lock state different from what it started but
1380** still short of its goal. The following chart shows the allowed
1381** transitions and the inserted intermediate states:
1382**
1383** UNLOCKED -> SHARED
1384** SHARED -> RESERVED
1385** SHARED -> (PENDING) -> EXCLUSIVE
1386** RESERVED -> (PENDING) -> EXCLUSIVE
1387** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001388**
drha6abd042004-06-09 17:37:22 +00001389** This routine will only increase a lock. Use the sqlite3OsUnlock()
1390** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001391*/
drh308c2a52010-05-14 11:30:18 +00001392static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001393 /* The following describes the implementation of the various locks and
1394 ** lock transitions in terms of the POSIX advisory shared and exclusive
1395 ** lock primitives (called read-locks and write-locks below, to avoid
1396 ** confusion with SQLite lock names). The algorithms are complicated
1397 ** slightly in order to be compatible with windows systems simultaneously
1398 ** accessing the same database file, in case that is ever required.
1399 **
1400 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1401 ** byte', each single bytes at well known offsets, and the 'shared byte
1402 ** range', a range of 510 bytes at a well known offset.
1403 **
1404 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1405 ** byte'. If this is successful, a random byte from the 'shared byte
1406 ** range' is read-locked and the lock on the 'pending byte' released.
1407 **
danielk197790ba3bd2004-06-25 08:32:25 +00001408 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1409 ** A RESERVED lock is implemented by grabbing a write-lock on the
1410 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001411 **
1412 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001413 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1414 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1415 ** obtained, but existing SHARED locks are allowed to persist. A process
1416 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1417 ** This property is used by the algorithm for rolling back a journal file
1418 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001419 **
danielk197790ba3bd2004-06-25 08:32:25 +00001420 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1421 ** implemented by obtaining a write-lock on the entire 'shared byte
1422 ** range'. Since all other locks require a read-lock on one of the bytes
1423 ** within this range, this ensures that no other locks are held on the
1424 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001425 **
1426 ** The reason a single byte cannot be used instead of the 'shared byte
1427 ** range' is that some versions of windows do not support read-locks. By
1428 ** locking a random byte from a range, concurrent SHARED locks may exist
1429 ** even if the locking primitive used is always a write-lock.
1430 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001431 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001432 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001433 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001434 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001435 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001436
drh054889e2005-11-30 03:20:31 +00001437 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001438 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1439 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001440 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001441
1442 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001443 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001444 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001445 */
drh308c2a52010-05-14 11:30:18 +00001446 if( pFile->eFileLock>=eFileLock ){
1447 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1448 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001449 return SQLITE_OK;
1450 }
1451
drh0c2694b2009-09-03 16:23:44 +00001452 /* Make sure the locking sequence is correct.
1453 ** (1) We never move from unlocked to anything higher than shared lock.
1454 ** (2) SQLite never explicitly requests a pendig lock.
1455 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001456 */
drh308c2a52010-05-14 11:30:18 +00001457 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1458 assert( eFileLock!=PENDING_LOCK );
1459 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001460
drh8af6c222010-05-14 12:43:01 +00001461 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001462 */
drh6c7d5c52008-11-21 20:32:33 +00001463 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001464 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001465
danielk1977ad94b582007-08-20 06:44:22 +00001466 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001467 ** handle that precludes the requested lock, return BUSY.
1468 */
drh8af6c222010-05-14 12:43:01 +00001469 if( (pFile->eFileLock!=pInode->eFileLock &&
1470 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001471 ){
1472 rc = SQLITE_BUSY;
1473 goto end_lock;
1474 }
1475
1476 /* If a SHARED lock is requested, and some thread using this PID already
1477 ** has a SHARED or RESERVED lock, then increment reference counts and
1478 ** return SQLITE_OK.
1479 */
drh308c2a52010-05-14 11:30:18 +00001480 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001481 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001482 assert( eFileLock==SHARED_LOCK );
1483 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001484 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001485 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001486 pInode->nShared++;
1487 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001488 goto end_lock;
1489 }
1490
danielk19779a1d0ab2004-06-01 14:09:28 +00001491
drh3cde3bb2004-06-12 02:17:14 +00001492 /* A PENDING lock is needed before acquiring a SHARED lock and before
1493 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1494 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001495 */
drh0c2694b2009-09-03 16:23:44 +00001496 lock.l_len = 1L;
1497 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001498 if( eFileLock==SHARED_LOCK
1499 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001500 ){
drh308c2a52010-05-14 11:30:18 +00001501 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001502 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001503 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001504 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001505 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001506 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001507 pFile->lastErrno = tErrno;
1508 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001509 goto end_lock;
1510 }
drh3cde3bb2004-06-12 02:17:14 +00001511 }
1512
1513
1514 /* If control gets to this point, then actually go ahead and make
1515 ** operating system calls for the specified lock.
1516 */
drh308c2a52010-05-14 11:30:18 +00001517 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001518 assert( pInode->nShared==0 );
1519 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001520 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001521
drh2ac3ee92004-06-07 16:27:46 +00001522 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001523 lock.l_start = SHARED_FIRST;
1524 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001525 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001526 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001527 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001528 }
dan661d71a2011-03-30 19:08:03 +00001529
drh2ac3ee92004-06-07 16:27:46 +00001530 /* Drop the temporary PENDING lock */
1531 lock.l_start = PENDING_BYTE;
1532 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001533 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001534 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1535 /* This could happen with a network mount */
1536 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001537 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001538 }
dan661d71a2011-03-30 19:08:03 +00001539
1540 if( rc ){
1541 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001542 pFile->lastErrno = tErrno;
1543 }
dan661d71a2011-03-30 19:08:03 +00001544 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001545 }else{
drh308c2a52010-05-14 11:30:18 +00001546 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001547 pInode->nLock++;
1548 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001549 }
drh8af6c222010-05-14 12:43:01 +00001550 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001551 /* We are trying for an exclusive lock but another thread in this
1552 ** same process is still holding a shared lock. */
1553 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001554 }else{
drh3cde3bb2004-06-12 02:17:14 +00001555 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001556 ** assumed that there is a SHARED or greater lock on the file
1557 ** already.
1558 */
drh308c2a52010-05-14 11:30:18 +00001559 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001560 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001561
1562 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1563 if( eFileLock==RESERVED_LOCK ){
1564 lock.l_start = RESERVED_BYTE;
1565 lock.l_len = 1L;
1566 }else{
1567 lock.l_start = SHARED_FIRST;
1568 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001569 }
dan661d71a2011-03-30 19:08:03 +00001570
1571 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001572 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001573 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001574 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001575 pFile->lastErrno = tErrno;
1576 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001577 }
drhbbd42a62004-05-22 17:41:58 +00001578 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001579
drh8f941bc2009-01-14 23:03:40 +00001580
drhd3d8c042012-05-29 17:02:40 +00001581#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001582 /* Set up the transaction-counter change checking flags when
1583 ** transitioning from a SHARED to a RESERVED lock. The change
1584 ** from SHARED to RESERVED marks the beginning of a normal
1585 ** write operation (not a hot journal rollback).
1586 */
1587 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001588 && pFile->eFileLock<=SHARED_LOCK
1589 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001590 ){
1591 pFile->transCntrChng = 0;
1592 pFile->dbUpdate = 0;
1593 pFile->inNormalWrite = 1;
1594 }
1595#endif
1596
1597
danielk1977ecb2a962004-06-02 06:30:16 +00001598 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001599 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001600 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001601 }else if( eFileLock==EXCLUSIVE_LOCK ){
1602 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001603 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001604 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001605
1606end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001607 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001608 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1609 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001610 return rc;
1611}
1612
1613/*
dan08da86a2009-08-21 17:18:03 +00001614** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001615** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001616*/
1617static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001618 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001619 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001620 p->pNext = pInode->pUnused;
1621 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001622 pFile->h = -1;
1623 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001624}
1625
1626/*
drh308c2a52010-05-14 11:30:18 +00001627** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001628** must be either NO_LOCK or SHARED_LOCK.
1629**
1630** If the locking level of the file descriptor is already at or below
1631** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001632**
1633** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1634** the byte range is divided into 2 parts and the first part is unlocked then
1635** set to a read lock, then the other part is simply unlocked. This works
1636** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1637** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001638*/
drha7e61d82011-03-12 17:02:57 +00001639static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001640 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001641 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001642 struct flock lock;
1643 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001644
drh054889e2005-11-30 03:20:31 +00001645 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001646 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001647 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001648 getpid()));
drha6abd042004-06-09 17:37:22 +00001649
drh308c2a52010-05-14 11:30:18 +00001650 assert( eFileLock<=SHARED_LOCK );
1651 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001652 return SQLITE_OK;
1653 }
drh6c7d5c52008-11-21 20:32:33 +00001654 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001655 pInode = pFile->pInode;
1656 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001657 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001658 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001659
drhd3d8c042012-05-29 17:02:40 +00001660#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001661 /* When reducing a lock such that other processes can start
1662 ** reading the database file again, make sure that the
1663 ** transaction counter was updated if any part of the database
1664 ** file changed. If the transaction counter is not updated,
1665 ** other connections to the same file might not realize that
1666 ** the file has changed and hence might not know to flush their
1667 ** cache. The use of a stale cache can lead to database corruption.
1668 */
drh8f941bc2009-01-14 23:03:40 +00001669 pFile->inNormalWrite = 0;
1670#endif
1671
drh7ed97b92010-01-20 13:07:21 +00001672 /* downgrading to a shared lock on NFS involves clearing the write lock
1673 ** before establishing the readlock - to avoid a race condition we downgrade
1674 ** the lock in 2 blocks, so that part of the range will be covered by a
1675 ** write lock until the rest is covered by a read lock:
1676 ** 1: [WWWWW]
1677 ** 2: [....W]
1678 ** 3: [RRRRW]
1679 ** 4: [RRRR.]
1680 */
drh308c2a52010-05-14 11:30:18 +00001681 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001682
1683#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001684 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001685 assert( handleNFSUnlock==0 );
1686#endif
1687#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001688 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001689 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001690 off_t divSize = SHARED_SIZE - 1;
1691
1692 lock.l_type = F_UNLCK;
1693 lock.l_whence = SEEK_SET;
1694 lock.l_start = SHARED_FIRST;
1695 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001696 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001697 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001698 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001699 if( IS_LOCK_ERROR(rc) ){
1700 pFile->lastErrno = tErrno;
1701 }
1702 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001703 }
drh7ed97b92010-01-20 13:07:21 +00001704 lock.l_type = F_RDLCK;
1705 lock.l_whence = SEEK_SET;
1706 lock.l_start = SHARED_FIRST;
1707 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001708 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001709 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001710 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1711 if( IS_LOCK_ERROR(rc) ){
1712 pFile->lastErrno = tErrno;
1713 }
1714 goto end_unlock;
1715 }
1716 lock.l_type = F_UNLCK;
1717 lock.l_whence = SEEK_SET;
1718 lock.l_start = SHARED_FIRST+divSize;
1719 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001720 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001721 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001722 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001723 if( IS_LOCK_ERROR(rc) ){
1724 pFile->lastErrno = tErrno;
1725 }
1726 goto end_unlock;
1727 }
drh30f776f2011-02-25 03:25:07 +00001728 }else
1729#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1730 {
drh7ed97b92010-01-20 13:07:21 +00001731 lock.l_type = F_RDLCK;
1732 lock.l_whence = SEEK_SET;
1733 lock.l_start = SHARED_FIRST;
1734 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001735 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001736 /* In theory, the call to unixFileLock() cannot fail because another
1737 ** process is holding an incompatible lock. If it does, this
1738 ** indicates that the other process is not following the locking
1739 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1740 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1741 ** an assert to fail). */
1742 rc = SQLITE_IOERR_RDLOCK;
1743 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001744 goto end_unlock;
1745 }
drh9c105bb2004-10-02 20:38:28 +00001746 }
1747 }
drhbbd42a62004-05-22 17:41:58 +00001748 lock.l_type = F_UNLCK;
1749 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001750 lock.l_start = PENDING_BYTE;
1751 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001752 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001753 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001754 }else{
danea83bc62011-04-01 11:56:32 +00001755 rc = SQLITE_IOERR_UNLOCK;
1756 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001757 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001758 }
drhbbd42a62004-05-22 17:41:58 +00001759 }
drh308c2a52010-05-14 11:30:18 +00001760 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001761 /* Decrement the shared lock counter. Release the lock using an
1762 ** OS call only when all threads in this same process have released
1763 ** the lock.
1764 */
drh8af6c222010-05-14 12:43:01 +00001765 pInode->nShared--;
1766 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001767 lock.l_type = F_UNLCK;
1768 lock.l_whence = SEEK_SET;
1769 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001770 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001771 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001772 }else{
danea83bc62011-04-01 11:56:32 +00001773 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001774 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001775 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001776 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001777 }
drha6abd042004-06-09 17:37:22 +00001778 }
1779
drhbbd42a62004-05-22 17:41:58 +00001780 /* Decrement the count of locks against this same file. When the
1781 ** count reaches zero, close any other file descriptors whose close
1782 ** was deferred because of outstanding locks.
1783 */
drh8af6c222010-05-14 12:43:01 +00001784 pInode->nLock--;
1785 assert( pInode->nLock>=0 );
1786 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001787 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001788 }
1789 }
drhf2f105d2012-08-20 15:53:54 +00001790
aswift5b1a2562008-08-22 00:22:35 +00001791end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001792 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001793 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001794 return rc;
drhbbd42a62004-05-22 17:41:58 +00001795}
1796
1797/*
drh308c2a52010-05-14 11:30:18 +00001798** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001799** must be either NO_LOCK or SHARED_LOCK.
1800**
1801** If the locking level of the file descriptor is already at or below
1802** the requested locking level, this routine is a no-op.
1803*/
drh308c2a52010-05-14 11:30:18 +00001804static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001805 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001806}
1807
1808/*
danielk1977e339d652008-06-28 11:23:00 +00001809** This function performs the parts of the "close file" operation
1810** common to all locking schemes. It closes the directory and file
1811** handles, if they are valid, and sets all fields of the unixFile
1812** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001813**
1814** It is *not* necessary to hold the mutex when this routine is called,
1815** even on VxWorks. A mutex will be acquired on VxWorks by the
1816** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001817*/
1818static int closeUnixFile(sqlite3_file *id){
1819 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001820 if( pFile->h>=0 ){
1821 robust_close(pFile, pFile->h, __LINE__);
1822 pFile->h = -1;
1823 }
1824#if OS_VXWORKS
1825 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001826 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001827 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001828 }
1829 vxworksReleaseFileId(pFile->pId);
1830 pFile->pId = 0;
1831 }
1832#endif
1833 OSTRACE(("CLOSE %-3d\n", pFile->h));
1834 OpenCounter(-1);
1835 sqlite3_free(pFile->pUnused);
1836 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001837 return SQLITE_OK;
1838}
1839
1840/*
danielk1977e3026632004-06-22 11:29:02 +00001841** Close a file.
1842*/
danielk197762079062007-08-15 17:08:46 +00001843static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001844 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001845 unixFile *pFile = (unixFile *)id;
1846 unixUnlock(id, NO_LOCK);
1847 unixEnterMutex();
1848
1849 /* unixFile.pInode is always valid here. Otherwise, a different close
1850 ** routine (e.g. nolockClose()) would be called instead.
1851 */
1852 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1853 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1854 /* If there are outstanding locks, do not actually close the file just
1855 ** yet because that would clear those locks. Instead, add the file
1856 ** descriptor to pInode->pUnused list. It will be automatically closed
1857 ** when the last lock is cleared.
1858 */
1859 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001860 }
dan661d71a2011-03-30 19:08:03 +00001861 releaseInodeInfo(pFile);
1862 rc = closeUnixFile(id);
1863 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001864 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001865}
1866
drh734c9862008-11-28 15:37:20 +00001867/************** End of the posix advisory lock implementation *****************
1868******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001869
drh734c9862008-11-28 15:37:20 +00001870/******************************************************************************
1871****************************** No-op Locking **********************************
1872**
1873** Of the various locking implementations available, this is by far the
1874** simplest: locking is ignored. No attempt is made to lock the database
1875** file for reading or writing.
1876**
1877** This locking mode is appropriate for use on read-only databases
1878** (ex: databases that are burned into CD-ROM, for example.) It can
1879** also be used if the application employs some external mechanism to
1880** prevent simultaneous access of the same database by two or more
1881** database connections. But there is a serious risk of database
1882** corruption if this locking mode is used in situations where multiple
1883** database connections are accessing the same database file at the same
1884** time and one or more of those connections are writing.
1885*/
drhbfe66312006-10-03 17:40:40 +00001886
drh734c9862008-11-28 15:37:20 +00001887static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1888 UNUSED_PARAMETER(NotUsed);
1889 *pResOut = 0;
1890 return SQLITE_OK;
1891}
drh734c9862008-11-28 15:37:20 +00001892static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1893 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1894 return SQLITE_OK;
1895}
drh734c9862008-11-28 15:37:20 +00001896static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1897 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1898 return SQLITE_OK;
1899}
1900
1901/*
drh9b35ea62008-11-29 02:20:26 +00001902** Close the file.
drh734c9862008-11-28 15:37:20 +00001903*/
1904static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001905 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001906}
1907
1908/******************* End of the no-op lock implementation *********************
1909******************************************************************************/
1910
1911/******************************************************************************
1912************************* Begin dot-file Locking ******************************
1913**
drh0c2694b2009-09-03 16:23:44 +00001914** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001915** files (really a directory) to control access to the database. This works
1916** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001917**
1918** (1) There is zero concurrency. A single reader blocks all other
1919** connections from reading or writing the database.
1920**
1921** (2) An application crash or power loss can leave stale lock files
1922** sitting around that need to be cleared manually.
1923**
1924** Nevertheless, a dotlock is an appropriate locking mode for use if no
1925** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001926**
drh9ef6bc42011-11-04 02:24:02 +00001927** Dotfile locking works by creating a subdirectory in the same directory as
1928** the database and with the same name but with a ".lock" extension added.
1929** The existance of a lock directory implies an EXCLUSIVE lock. All other
1930** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001931*/
1932
1933/*
1934** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001935** lock directory.
drh734c9862008-11-28 15:37:20 +00001936*/
1937#define DOTLOCK_SUFFIX ".lock"
1938
drh7708e972008-11-29 00:56:52 +00001939/*
1940** This routine checks if there is a RESERVED lock held on the specified
1941** file by this or any other process. If such a lock is held, set *pResOut
1942** to a non-zero value otherwise *pResOut is set to zero. The return value
1943** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1944**
1945** In dotfile locking, either a lock exists or it does not. So in this
1946** variation of CheckReservedLock(), *pResOut is set to true if any lock
1947** is held on the file and false if the file is unlocked.
1948*/
drh734c9862008-11-28 15:37:20 +00001949static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1950 int rc = SQLITE_OK;
1951 int reserved = 0;
1952 unixFile *pFile = (unixFile*)id;
1953
1954 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1955
1956 assert( pFile );
1957
1958 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001959 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001960 /* Either this connection or some other connection in the same process
1961 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001962 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001963 }else{
1964 /* The lock is held if and only if the lockfile exists */
1965 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001966 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001967 }
drh308c2a52010-05-14 11:30:18 +00001968 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001969 *pResOut = reserved;
1970 return rc;
1971}
1972
drh7708e972008-11-29 00:56:52 +00001973/*
drh308c2a52010-05-14 11:30:18 +00001974** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001975** of the following:
1976**
1977** (1) SHARED_LOCK
1978** (2) RESERVED_LOCK
1979** (3) PENDING_LOCK
1980** (4) EXCLUSIVE_LOCK
1981**
1982** Sometimes when requesting one lock state, additional lock states
1983** are inserted in between. The locking might fail on one of the later
1984** transitions leaving the lock state different from what it started but
1985** still short of its goal. The following chart shows the allowed
1986** transitions and the inserted intermediate states:
1987**
1988** UNLOCKED -> SHARED
1989** SHARED -> RESERVED
1990** SHARED -> (PENDING) -> EXCLUSIVE
1991** RESERVED -> (PENDING) -> EXCLUSIVE
1992** PENDING -> EXCLUSIVE
1993**
1994** This routine will only increase a lock. Use the sqlite3OsUnlock()
1995** routine to lower a locking level.
1996**
1997** With dotfile locking, we really only support state (4): EXCLUSIVE.
1998** But we track the other locking levels internally.
1999*/
drh308c2a52010-05-14 11:30:18 +00002000static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002001 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002002 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002003 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002004
drh7708e972008-11-29 00:56:52 +00002005
2006 /* If we have any lock, then the lock file already exists. All we have
2007 ** to do is adjust our internal record of the lock level.
2008 */
drh308c2a52010-05-14 11:30:18 +00002009 if( pFile->eFileLock > NO_LOCK ){
2010 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002011 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002012#ifdef HAVE_UTIME
2013 utime(zLockFile, NULL);
2014#else
drh734c9862008-11-28 15:37:20 +00002015 utimes(zLockFile, NULL);
2016#endif
drh7708e972008-11-29 00:56:52 +00002017 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002018 }
2019
2020 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002021 rc = osMkdir(zLockFile, 0777);
2022 if( rc<0 ){
2023 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002024 int tErrno = errno;
2025 if( EEXIST == tErrno ){
2026 rc = SQLITE_BUSY;
2027 } else {
2028 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2029 if( IS_LOCK_ERROR(rc) ){
2030 pFile->lastErrno = tErrno;
2031 }
2032 }
drh7708e972008-11-29 00:56:52 +00002033 return rc;
drh734c9862008-11-28 15:37:20 +00002034 }
drh734c9862008-11-28 15:37:20 +00002035
2036 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002037 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002038 return rc;
2039}
2040
drh7708e972008-11-29 00:56:52 +00002041/*
drh308c2a52010-05-14 11:30:18 +00002042** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002043** must be either NO_LOCK or SHARED_LOCK.
2044**
2045** If the locking level of the file descriptor is already at or below
2046** the requested locking level, this routine is a no-op.
2047**
2048** When the locking level reaches NO_LOCK, delete the lock file.
2049*/
drh308c2a52010-05-14 11:30:18 +00002050static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002051 unixFile *pFile = (unixFile*)id;
2052 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002053 int rc;
drh734c9862008-11-28 15:37:20 +00002054
2055 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002056 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002057 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002058 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002059
2060 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002061 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002062 return SQLITE_OK;
2063 }
drh7708e972008-11-29 00:56:52 +00002064
2065 /* To downgrade to shared, simply update our internal notion of the
2066 ** lock state. No need to mess with the file on disk.
2067 */
drh308c2a52010-05-14 11:30:18 +00002068 if( eFileLock==SHARED_LOCK ){
2069 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002070 return SQLITE_OK;
2071 }
2072
drh7708e972008-11-29 00:56:52 +00002073 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002074 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002075 rc = osRmdir(zLockFile);
2076 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2077 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002078 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002079 rc = 0;
drh734c9862008-11-28 15:37:20 +00002080 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002081 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002082 }
2083 if( IS_LOCK_ERROR(rc) ){
2084 pFile->lastErrno = tErrno;
2085 }
2086 return rc;
2087 }
drh308c2a52010-05-14 11:30:18 +00002088 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002089 return SQLITE_OK;
2090}
2091
2092/*
drh9b35ea62008-11-29 02:20:26 +00002093** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002094*/
2095static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002096 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002097 if( id ){
2098 unixFile *pFile = (unixFile*)id;
2099 dotlockUnlock(id, NO_LOCK);
2100 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002101 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002102 }
drh734c9862008-11-28 15:37:20 +00002103 return rc;
2104}
2105/****************** End of the dot-file lock implementation *******************
2106******************************************************************************/
2107
2108/******************************************************************************
2109************************** Begin flock Locking ********************************
2110**
2111** Use the flock() system call to do file locking.
2112**
drh6b9d6dd2008-12-03 19:34:47 +00002113** flock() locking is like dot-file locking in that the various
2114** fine-grain locking levels supported by SQLite are collapsed into
2115** a single exclusive lock. In other words, SHARED, RESERVED, and
2116** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2117** still works when you do this, but concurrency is reduced since
2118** only a single process can be reading the database at a time.
2119**
drh734c9862008-11-28 15:37:20 +00002120** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2121** compiling for VXWORKS.
2122*/
2123#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002124
drh6b9d6dd2008-12-03 19:34:47 +00002125/*
drhff812312011-02-23 13:33:46 +00002126** Retry flock() calls that fail with EINTR
2127*/
2128#ifdef EINTR
2129static int robust_flock(int fd, int op){
2130 int rc;
2131 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2132 return rc;
2133}
2134#else
drh5c819272011-02-23 14:00:12 +00002135# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002136#endif
2137
2138
2139/*
drh6b9d6dd2008-12-03 19:34:47 +00002140** This routine checks if there is a RESERVED lock held on the specified
2141** file by this or any other process. If such a lock is held, set *pResOut
2142** to a non-zero value otherwise *pResOut is set to zero. The return value
2143** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2144*/
drh734c9862008-11-28 15:37:20 +00002145static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2146 int rc = SQLITE_OK;
2147 int reserved = 0;
2148 unixFile *pFile = (unixFile*)id;
2149
2150 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2151
2152 assert( pFile );
2153
2154 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002155 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002156 reserved = 1;
2157 }
2158
2159 /* Otherwise see if some other process holds it. */
2160 if( !reserved ){
2161 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002162 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002163 if( !lrc ){
2164 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002165 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002166 if ( lrc ) {
2167 int tErrno = errno;
2168 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002169 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002170 if( IS_LOCK_ERROR(lrc) ){
2171 pFile->lastErrno = tErrno;
2172 rc = lrc;
2173 }
2174 }
2175 } else {
2176 int tErrno = errno;
2177 reserved = 1;
2178 /* someone else might have it reserved */
2179 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2180 if( IS_LOCK_ERROR(lrc) ){
2181 pFile->lastErrno = tErrno;
2182 rc = lrc;
2183 }
2184 }
2185 }
drh308c2a52010-05-14 11:30:18 +00002186 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002187
2188#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2189 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2190 rc = SQLITE_OK;
2191 reserved=1;
2192 }
2193#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2194 *pResOut = reserved;
2195 return rc;
2196}
2197
drh6b9d6dd2008-12-03 19:34:47 +00002198/*
drh308c2a52010-05-14 11:30:18 +00002199** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002200** of the following:
2201**
2202** (1) SHARED_LOCK
2203** (2) RESERVED_LOCK
2204** (3) PENDING_LOCK
2205** (4) EXCLUSIVE_LOCK
2206**
2207** Sometimes when requesting one lock state, additional lock states
2208** are inserted in between. The locking might fail on one of the later
2209** transitions leaving the lock state different from what it started but
2210** still short of its goal. The following chart shows the allowed
2211** transitions and the inserted intermediate states:
2212**
2213** UNLOCKED -> SHARED
2214** SHARED -> RESERVED
2215** SHARED -> (PENDING) -> EXCLUSIVE
2216** RESERVED -> (PENDING) -> EXCLUSIVE
2217** PENDING -> EXCLUSIVE
2218**
2219** flock() only really support EXCLUSIVE locks. We track intermediate
2220** lock states in the sqlite3_file structure, but all locks SHARED or
2221** above are really EXCLUSIVE locks and exclude all other processes from
2222** access the file.
2223**
2224** This routine will only increase a lock. Use the sqlite3OsUnlock()
2225** routine to lower a locking level.
2226*/
drh308c2a52010-05-14 11:30:18 +00002227static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002228 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002229 unixFile *pFile = (unixFile*)id;
2230
2231 assert( pFile );
2232
2233 /* if we already have a lock, it is exclusive.
2234 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002235 if (pFile->eFileLock > NO_LOCK) {
2236 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002237 return SQLITE_OK;
2238 }
2239
2240 /* grab an exclusive lock */
2241
drhff812312011-02-23 13:33:46 +00002242 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002243 int tErrno = errno;
2244 /* didn't get, must be busy */
2245 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2246 if( IS_LOCK_ERROR(rc) ){
2247 pFile->lastErrno = tErrno;
2248 }
2249 } else {
2250 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002251 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002252 }
drh308c2a52010-05-14 11:30:18 +00002253 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2254 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002255#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2256 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2257 rc = SQLITE_BUSY;
2258 }
2259#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2260 return rc;
2261}
2262
drh6b9d6dd2008-12-03 19:34:47 +00002263
2264/*
drh308c2a52010-05-14 11:30:18 +00002265** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002266** must be either NO_LOCK or SHARED_LOCK.
2267**
2268** If the locking level of the file descriptor is already at or below
2269** the requested locking level, this routine is a no-op.
2270*/
drh308c2a52010-05-14 11:30:18 +00002271static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002272 unixFile *pFile = (unixFile*)id;
2273
2274 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002275 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2276 pFile->eFileLock, getpid()));
2277 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002278
2279 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002280 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002281 return SQLITE_OK;
2282 }
2283
2284 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002285 if (eFileLock==SHARED_LOCK) {
2286 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002287 return SQLITE_OK;
2288 }
2289
2290 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002291 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002292#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002293 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002294#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002295 return SQLITE_IOERR_UNLOCK;
2296 }else{
drh308c2a52010-05-14 11:30:18 +00002297 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002298 return SQLITE_OK;
2299 }
2300}
2301
2302/*
2303** Close a file.
2304*/
2305static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002306 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002307 if( id ){
2308 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002309 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002310 }
drh5a05be12012-10-09 18:51:44 +00002311 return rc;
drh734c9862008-11-28 15:37:20 +00002312}
2313
2314#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2315
2316/******************* End of the flock lock implementation *********************
2317******************************************************************************/
2318
2319/******************************************************************************
2320************************ Begin Named Semaphore Locking ************************
2321**
2322** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002323**
2324** Semaphore locking is like dot-lock and flock in that it really only
2325** supports EXCLUSIVE locking. Only a single process can read or write
2326** the database file at a time. This reduces potential concurrency, but
2327** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002328*/
2329#if OS_VXWORKS
2330
drh6b9d6dd2008-12-03 19:34:47 +00002331/*
2332** This routine checks if there is a RESERVED lock held on the specified
2333** file by this or any other process. If such a lock is held, set *pResOut
2334** to a non-zero value otherwise *pResOut is set to zero. The return value
2335** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2336*/
drh734c9862008-11-28 15:37:20 +00002337static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2338 int rc = SQLITE_OK;
2339 int reserved = 0;
2340 unixFile *pFile = (unixFile*)id;
2341
2342 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2343
2344 assert( pFile );
2345
2346 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002347 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002348 reserved = 1;
2349 }
2350
2351 /* Otherwise see if some other process holds it. */
2352 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002353 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002354 struct stat statBuf;
2355
2356 if( sem_trywait(pSem)==-1 ){
2357 int tErrno = errno;
2358 if( EAGAIN != tErrno ){
2359 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2360 pFile->lastErrno = tErrno;
2361 } else {
2362 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002363 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002364 }
2365 }else{
2366 /* we could have it if we want it */
2367 sem_post(pSem);
2368 }
2369 }
drh308c2a52010-05-14 11:30:18 +00002370 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002371
2372 *pResOut = reserved;
2373 return rc;
2374}
2375
drh6b9d6dd2008-12-03 19:34:47 +00002376/*
drh308c2a52010-05-14 11:30:18 +00002377** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002378** of the following:
2379**
2380** (1) SHARED_LOCK
2381** (2) RESERVED_LOCK
2382** (3) PENDING_LOCK
2383** (4) EXCLUSIVE_LOCK
2384**
2385** Sometimes when requesting one lock state, additional lock states
2386** are inserted in between. The locking might fail on one of the later
2387** transitions leaving the lock state different from what it started but
2388** still short of its goal. The following chart shows the allowed
2389** transitions and the inserted intermediate states:
2390**
2391** UNLOCKED -> SHARED
2392** SHARED -> RESERVED
2393** SHARED -> (PENDING) -> EXCLUSIVE
2394** RESERVED -> (PENDING) -> EXCLUSIVE
2395** PENDING -> EXCLUSIVE
2396**
2397** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2398** lock states in the sqlite3_file structure, but all locks SHARED or
2399** above are really EXCLUSIVE locks and exclude all other processes from
2400** access the file.
2401**
2402** This routine will only increase a lock. Use the sqlite3OsUnlock()
2403** routine to lower a locking level.
2404*/
drh308c2a52010-05-14 11:30:18 +00002405static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002406 unixFile *pFile = (unixFile*)id;
2407 int fd;
drh8af6c222010-05-14 12:43:01 +00002408 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002409 int rc = SQLITE_OK;
2410
2411 /* if we already have a lock, it is exclusive.
2412 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002413 if (pFile->eFileLock > NO_LOCK) {
2414 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002415 rc = SQLITE_OK;
2416 goto sem_end_lock;
2417 }
2418
2419 /* lock semaphore now but bail out when already locked. */
2420 if( sem_trywait(pSem)==-1 ){
2421 rc = SQLITE_BUSY;
2422 goto sem_end_lock;
2423 }
2424
2425 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002426 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002427
2428 sem_end_lock:
2429 return rc;
2430}
2431
drh6b9d6dd2008-12-03 19:34:47 +00002432/*
drh308c2a52010-05-14 11:30:18 +00002433** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002434** must be either NO_LOCK or SHARED_LOCK.
2435**
2436** If the locking level of the file descriptor is already at or below
2437** the requested locking level, this routine is a no-op.
2438*/
drh308c2a52010-05-14 11:30:18 +00002439static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002440 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002441 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002442
2443 assert( pFile );
2444 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002445 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002446 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002447 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002448
2449 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002450 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002451 return SQLITE_OK;
2452 }
2453
2454 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002455 if (eFileLock==SHARED_LOCK) {
2456 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002457 return SQLITE_OK;
2458 }
2459
2460 /* no, really unlock. */
2461 if ( sem_post(pSem)==-1 ) {
2462 int rc, tErrno = errno;
2463 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2464 if( IS_LOCK_ERROR(rc) ){
2465 pFile->lastErrno = tErrno;
2466 }
2467 return rc;
2468 }
drh308c2a52010-05-14 11:30:18 +00002469 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002470 return SQLITE_OK;
2471}
2472
2473/*
2474 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002475 */
drh734c9862008-11-28 15:37:20 +00002476static int semClose(sqlite3_file *id) {
2477 if( id ){
2478 unixFile *pFile = (unixFile*)id;
2479 semUnlock(id, NO_LOCK);
2480 assert( pFile );
2481 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002482 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002483 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002484 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002485 }
2486 return SQLITE_OK;
2487}
2488
2489#endif /* OS_VXWORKS */
2490/*
2491** Named semaphore locking is only available on VxWorks.
2492**
2493*************** End of the named semaphore lock implementation ****************
2494******************************************************************************/
2495
2496
2497/******************************************************************************
2498*************************** Begin AFP Locking *********************************
2499**
2500** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2501** on Apple Macintosh computers - both OS9 and OSX.
2502**
2503** Third-party implementations of AFP are available. But this code here
2504** only works on OSX.
2505*/
2506
drhd2cb50b2009-01-09 21:41:17 +00002507#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002508/*
2509** The afpLockingContext structure contains all afp lock specific state
2510*/
drhbfe66312006-10-03 17:40:40 +00002511typedef struct afpLockingContext afpLockingContext;
2512struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002513 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002514 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002515};
2516
2517struct ByteRangeLockPB2
2518{
2519 unsigned long long offset; /* offset to first byte to lock */
2520 unsigned long long length; /* nbr of bytes to lock */
2521 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2522 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2523 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2524 int fd; /* file desc to assoc this lock with */
2525};
2526
drhfd131da2007-08-07 17:13:03 +00002527#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002528
drh6b9d6dd2008-12-03 19:34:47 +00002529/*
2530** This is a utility for setting or clearing a bit-range lock on an
2531** AFP filesystem.
2532**
2533** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2534*/
2535static int afpSetLock(
2536 const char *path, /* Name of the file to be locked or unlocked */
2537 unixFile *pFile, /* Open file descriptor on path */
2538 unsigned long long offset, /* First byte to be locked */
2539 unsigned long long length, /* Number of bytes to lock */
2540 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002541){
drh6b9d6dd2008-12-03 19:34:47 +00002542 struct ByteRangeLockPB2 pb;
2543 int err;
drhbfe66312006-10-03 17:40:40 +00002544
2545 pb.unLockFlag = setLockFlag ? 0 : 1;
2546 pb.startEndFlag = 0;
2547 pb.offset = offset;
2548 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002549 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002550
drh308c2a52010-05-14 11:30:18 +00002551 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002552 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002553 offset, length));
drhbfe66312006-10-03 17:40:40 +00002554 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2555 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002556 int rc;
2557 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002558 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2559 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002560#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2561 rc = SQLITE_BUSY;
2562#else
drh734c9862008-11-28 15:37:20 +00002563 rc = sqliteErrorFromPosixError(tErrno,
2564 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002565#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002566 if( IS_LOCK_ERROR(rc) ){
2567 pFile->lastErrno = tErrno;
2568 }
2569 return rc;
drhbfe66312006-10-03 17:40:40 +00002570 } else {
aswift5b1a2562008-08-22 00:22:35 +00002571 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002572 }
2573}
2574
drh6b9d6dd2008-12-03 19:34:47 +00002575/*
2576** This routine checks if there is a RESERVED lock held on the specified
2577** file by this or any other process. If such a lock is held, set *pResOut
2578** to a non-zero value otherwise *pResOut is set to zero. The return value
2579** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2580*/
danielk1977e339d652008-06-28 11:23:00 +00002581static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002582 int rc = SQLITE_OK;
2583 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002584 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002585 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002586
aswift5b1a2562008-08-22 00:22:35 +00002587 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2588
2589 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002590 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002591 if( context->reserved ){
2592 *pResOut = 1;
2593 return SQLITE_OK;
2594 }
drh8af6c222010-05-14 12:43:01 +00002595 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002596
2597 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002598 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002599 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002600 }
2601
2602 /* Otherwise see if some other process holds it.
2603 */
aswift5b1a2562008-08-22 00:22:35 +00002604 if( !reserved ){
2605 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002606 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002607 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002608 /* if we succeeded in taking the reserved lock, unlock it to restore
2609 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002610 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002611 } else {
2612 /* if we failed to get the lock then someone else must have it */
2613 reserved = 1;
2614 }
2615 if( IS_LOCK_ERROR(lrc) ){
2616 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002617 }
2618 }
drhbfe66312006-10-03 17:40:40 +00002619
drh7ed97b92010-01-20 13:07:21 +00002620 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002621 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002622
2623 *pResOut = reserved;
2624 return rc;
drhbfe66312006-10-03 17:40:40 +00002625}
2626
drh6b9d6dd2008-12-03 19:34:47 +00002627/*
drh308c2a52010-05-14 11:30:18 +00002628** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002629** of the following:
2630**
2631** (1) SHARED_LOCK
2632** (2) RESERVED_LOCK
2633** (3) PENDING_LOCK
2634** (4) EXCLUSIVE_LOCK
2635**
2636** Sometimes when requesting one lock state, additional lock states
2637** are inserted in between. The locking might fail on one of the later
2638** transitions leaving the lock state different from what it started but
2639** still short of its goal. The following chart shows the allowed
2640** transitions and the inserted intermediate states:
2641**
2642** UNLOCKED -> SHARED
2643** SHARED -> RESERVED
2644** SHARED -> (PENDING) -> EXCLUSIVE
2645** RESERVED -> (PENDING) -> EXCLUSIVE
2646** PENDING -> EXCLUSIVE
2647**
2648** This routine will only increase a lock. Use the sqlite3OsUnlock()
2649** routine to lower a locking level.
2650*/
drh308c2a52010-05-14 11:30:18 +00002651static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002652 int rc = SQLITE_OK;
2653 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002654 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002655 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002656
2657 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002658 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2659 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002660 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002661
drhbfe66312006-10-03 17:40:40 +00002662 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002663 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002664 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002665 */
drh308c2a52010-05-14 11:30:18 +00002666 if( pFile->eFileLock>=eFileLock ){
2667 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2668 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002669 return SQLITE_OK;
2670 }
2671
2672 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002673 ** (1) We never move from unlocked to anything higher than shared lock.
2674 ** (2) SQLite never explicitly requests a pendig lock.
2675 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002676 */
drh308c2a52010-05-14 11:30:18 +00002677 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2678 assert( eFileLock!=PENDING_LOCK );
2679 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002680
drh8af6c222010-05-14 12:43:01 +00002681 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002682 */
drh6c7d5c52008-11-21 20:32:33 +00002683 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002684 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002685
2686 /* If some thread using this PID has a lock via a different unixFile*
2687 ** handle that precludes the requested lock, return BUSY.
2688 */
drh8af6c222010-05-14 12:43:01 +00002689 if( (pFile->eFileLock!=pInode->eFileLock &&
2690 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002691 ){
2692 rc = SQLITE_BUSY;
2693 goto afp_end_lock;
2694 }
2695
2696 /* If a SHARED lock is requested, and some thread using this PID already
2697 ** has a SHARED or RESERVED lock, then increment reference counts and
2698 ** return SQLITE_OK.
2699 */
drh308c2a52010-05-14 11:30:18 +00002700 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002701 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002702 assert( eFileLock==SHARED_LOCK );
2703 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002704 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002705 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002706 pInode->nShared++;
2707 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002708 goto afp_end_lock;
2709 }
drhbfe66312006-10-03 17:40:40 +00002710
2711 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002712 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2713 ** be released.
2714 */
drh308c2a52010-05-14 11:30:18 +00002715 if( eFileLock==SHARED_LOCK
2716 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002717 ){
2718 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002719 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002720 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002721 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002722 goto afp_end_lock;
2723 }
2724 }
2725
2726 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002727 ** operating system calls for the specified lock.
2728 */
drh308c2a52010-05-14 11:30:18 +00002729 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002730 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002731 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002732
drh8af6c222010-05-14 12:43:01 +00002733 assert( pInode->nShared==0 );
2734 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002735
2736 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002737 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002738 /* note that the quality of the randomness doesn't matter that much */
2739 lk = random();
drh8af6c222010-05-14 12:43:01 +00002740 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002741 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002742 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002743 if( IS_LOCK_ERROR(lrc1) ){
2744 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002745 }
aswift5b1a2562008-08-22 00:22:35 +00002746 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002747 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002748
aswift5b1a2562008-08-22 00:22:35 +00002749 if( IS_LOCK_ERROR(lrc1) ) {
2750 pFile->lastErrno = lrc1Errno;
2751 rc = lrc1;
2752 goto afp_end_lock;
2753 } else if( IS_LOCK_ERROR(lrc2) ){
2754 rc = lrc2;
2755 goto afp_end_lock;
2756 } else if( lrc1 != SQLITE_OK ) {
2757 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002758 } else {
drh308c2a52010-05-14 11:30:18 +00002759 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002760 pInode->nLock++;
2761 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002762 }
drh8af6c222010-05-14 12:43:01 +00002763 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002764 /* We are trying for an exclusive lock but another thread in this
2765 ** same process is still holding a shared lock. */
2766 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002767 }else{
2768 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2769 ** assumed that there is a SHARED or greater lock on the file
2770 ** already.
2771 */
2772 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002773 assert( 0!=pFile->eFileLock );
2774 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002775 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002776 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002777 if( !failed ){
2778 context->reserved = 1;
2779 }
drhbfe66312006-10-03 17:40:40 +00002780 }
drh308c2a52010-05-14 11:30:18 +00002781 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002782 /* Acquire an EXCLUSIVE lock */
2783
2784 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002785 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002786 */
drh6b9d6dd2008-12-03 19:34:47 +00002787 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002788 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002789 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002790 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002791 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002792 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002793 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002794 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002795 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2796 ** a critical I/O error
2797 */
2798 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2799 SQLITE_IOERR_LOCK;
2800 goto afp_end_lock;
2801 }
2802 }else{
aswift5b1a2562008-08-22 00:22:35 +00002803 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002804 }
2805 }
aswift5b1a2562008-08-22 00:22:35 +00002806 if( failed ){
2807 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002808 }
2809 }
2810
2811 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002812 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002813 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002814 }else if( eFileLock==EXCLUSIVE_LOCK ){
2815 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002816 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002817 }
2818
2819afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002820 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002821 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2822 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002823 return rc;
2824}
2825
2826/*
drh308c2a52010-05-14 11:30:18 +00002827** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002828** must be either NO_LOCK or SHARED_LOCK.
2829**
2830** If the locking level of the file descriptor is already at or below
2831** the requested locking level, this routine is a no-op.
2832*/
drh308c2a52010-05-14 11:30:18 +00002833static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002834 int rc = SQLITE_OK;
2835 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002836 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002837 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2838 int skipShared = 0;
2839#ifdef SQLITE_TEST
2840 int h = pFile->h;
2841#endif
drhbfe66312006-10-03 17:40:40 +00002842
2843 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002844 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002845 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002846 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002847
drh308c2a52010-05-14 11:30:18 +00002848 assert( eFileLock<=SHARED_LOCK );
2849 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002850 return SQLITE_OK;
2851 }
drh6c7d5c52008-11-21 20:32:33 +00002852 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002853 pInode = pFile->pInode;
2854 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002855 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002856 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002857 SimulateIOErrorBenign(1);
2858 SimulateIOError( h=(-1) )
2859 SimulateIOErrorBenign(0);
2860
drhd3d8c042012-05-29 17:02:40 +00002861#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002862 /* When reducing a lock such that other processes can start
2863 ** reading the database file again, make sure that the
2864 ** transaction counter was updated if any part of the database
2865 ** file changed. If the transaction counter is not updated,
2866 ** other connections to the same file might not realize that
2867 ** the file has changed and hence might not know to flush their
2868 ** cache. The use of a stale cache can lead to database corruption.
2869 */
2870 assert( pFile->inNormalWrite==0
2871 || pFile->dbUpdate==0
2872 || pFile->transCntrChng==1 );
2873 pFile->inNormalWrite = 0;
2874#endif
aswiftaebf4132008-11-21 00:10:35 +00002875
drh308c2a52010-05-14 11:30:18 +00002876 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002877 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002878 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002879 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002880 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002881 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2882 } else {
2883 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002884 }
2885 }
drh308c2a52010-05-14 11:30:18 +00002886 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002887 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002888 }
drh308c2a52010-05-14 11:30:18 +00002889 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002890 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2891 if( !rc ){
2892 context->reserved = 0;
2893 }
aswiftaebf4132008-11-21 00:10:35 +00002894 }
drh8af6c222010-05-14 12:43:01 +00002895 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2896 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002897 }
aswiftaebf4132008-11-21 00:10:35 +00002898 }
drh308c2a52010-05-14 11:30:18 +00002899 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002900
drh7ed97b92010-01-20 13:07:21 +00002901 /* Decrement the shared lock counter. Release the lock using an
2902 ** OS call only when all threads in this same process have released
2903 ** the lock.
2904 */
drh8af6c222010-05-14 12:43:01 +00002905 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2906 pInode->nShared--;
2907 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002908 SimulateIOErrorBenign(1);
2909 SimulateIOError( h=(-1) )
2910 SimulateIOErrorBenign(0);
2911 if( !skipShared ){
2912 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2913 }
2914 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002915 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002916 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002917 }
2918 }
2919 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002920 pInode->nLock--;
2921 assert( pInode->nLock>=0 );
2922 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002923 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002924 }
2925 }
drhbfe66312006-10-03 17:40:40 +00002926 }
drh7ed97b92010-01-20 13:07:21 +00002927
drh6c7d5c52008-11-21 20:32:33 +00002928 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002929 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002930 return rc;
2931}
2932
2933/*
drh339eb0b2008-03-07 15:34:11 +00002934** Close a file & cleanup AFP specific locking context
2935*/
danielk1977e339d652008-06-28 11:23:00 +00002936static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002937 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002938 if( id ){
2939 unixFile *pFile = (unixFile*)id;
2940 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002941 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002942 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002943 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002944 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002945 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002946 ** the last lock is cleared.
2947 */
dan08da86a2009-08-21 17:18:03 +00002948 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002949 }
danb0ac3e32010-06-16 10:55:42 +00002950 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002951 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002952 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002953 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002954 }
drh7ed97b92010-01-20 13:07:21 +00002955 return rc;
drhbfe66312006-10-03 17:40:40 +00002956}
2957
drhd2cb50b2009-01-09 21:41:17 +00002958#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002959/*
2960** The code above is the AFP lock implementation. The code is specific
2961** to MacOSX and does not work on other unix platforms. No alternative
2962** is available. If you don't compile for a mac, then the "unix-afp"
2963** VFS is not available.
2964**
2965********************* End of the AFP lock implementation **********************
2966******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002967
drh7ed97b92010-01-20 13:07:21 +00002968/******************************************************************************
2969*************************** Begin NFS Locking ********************************/
2970
2971#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2972/*
drh308c2a52010-05-14 11:30:18 +00002973 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002974 ** must be either NO_LOCK or SHARED_LOCK.
2975 **
2976 ** If the locking level of the file descriptor is already at or below
2977 ** the requested locking level, this routine is a no-op.
2978 */
drh308c2a52010-05-14 11:30:18 +00002979static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002980 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002981}
2982
2983#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2984/*
2985** The code above is the NFS lock implementation. The code is specific
2986** to MacOSX and does not work on other unix platforms. No alternative
2987** is available.
2988**
2989********************* End of the NFS lock implementation **********************
2990******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002991
2992/******************************************************************************
2993**************** Non-locking sqlite3_file methods *****************************
2994**
2995** The next division contains implementations for all methods of the
2996** sqlite3_file object other than the locking methods. The locking
2997** methods were defined in divisions above (one locking method per
2998** division). Those methods that are common to all locking modes
2999** are gather together into this division.
3000*/
drhbfe66312006-10-03 17:40:40 +00003001
3002/*
drh734c9862008-11-28 15:37:20 +00003003** Seek to the offset passed as the second argument, then read cnt
3004** bytes into pBuf. Return the number of bytes actually read.
3005**
3006** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3007** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3008** one system to another. Since SQLite does not define USE_PREAD
3009** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3010** See tickets #2741 and #2681.
3011**
3012** To avoid stomping the errno value on a failed read the lastErrno value
3013** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003014*/
drh734c9862008-11-28 15:37:20 +00003015static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3016 int got;
drh58024642011-11-07 18:16:00 +00003017 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003018#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003019 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003020#endif
drh734c9862008-11-28 15:37:20 +00003021 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003022 assert( cnt==(cnt&0x1ffff) );
3023 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003024 do{
drh734c9862008-11-28 15:37:20 +00003025#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003026 got = osPread(id->h, pBuf, cnt, offset);
3027 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003028#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003029 got = osPread64(id->h, pBuf, cnt, offset);
3030 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003031#else
drh58024642011-11-07 18:16:00 +00003032 newOffset = lseek(id->h, offset, SEEK_SET);
3033 SimulateIOError( newOffset-- );
3034 if( newOffset!=offset ){
3035 if( newOffset == -1 ){
3036 ((unixFile*)id)->lastErrno = errno;
3037 }else{
drhf2f105d2012-08-20 15:53:54 +00003038 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003039 }
3040 return -1;
drh734c9862008-11-28 15:37:20 +00003041 }
drh58024642011-11-07 18:16:00 +00003042 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003043#endif
drh58024642011-11-07 18:16:00 +00003044 if( got==cnt ) break;
3045 if( got<0 ){
3046 if( errno==EINTR ){ got = 1; continue; }
3047 prior = 0;
3048 ((unixFile*)id)->lastErrno = errno;
3049 break;
3050 }else if( got>0 ){
3051 cnt -= got;
3052 offset += got;
3053 prior += got;
3054 pBuf = (void*)(got + (char*)pBuf);
3055 }
3056 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003057 TIMER_END;
drh58024642011-11-07 18:16:00 +00003058 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3059 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3060 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003061}
3062
3063/*
drh734c9862008-11-28 15:37:20 +00003064** Read data from a file into a buffer. Return SQLITE_OK if all
3065** bytes were read successfully and SQLITE_IOERR if anything goes
3066** wrong.
drh339eb0b2008-03-07 15:34:11 +00003067*/
drh734c9862008-11-28 15:37:20 +00003068static int unixRead(
3069 sqlite3_file *id,
3070 void *pBuf,
3071 int amt,
3072 sqlite3_int64 offset
3073){
dan08da86a2009-08-21 17:18:03 +00003074 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003075 int got;
3076 assert( id );
dan6101d502013-03-22 08:58:38 +00003077 assert( offset>=pFile->mmapSize ); /* Never read from the mmapped region */
drh08c6d442009-02-09 17:34:07 +00003078
dan08da86a2009-08-21 17:18:03 +00003079 /* If this is a database file (not a journal, master-journal or temp
3080 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003081#if 0
dane946c392009-08-22 11:39:46 +00003082 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003083 || offset>=PENDING_BYTE+512
3084 || offset+amt<=PENDING_BYTE
3085 );
dan7c246102010-04-12 19:00:29 +00003086#endif
drh08c6d442009-02-09 17:34:07 +00003087
dan08da86a2009-08-21 17:18:03 +00003088 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003089 if( got==amt ){
3090 return SQLITE_OK;
3091 }else if( got<0 ){
3092 /* lastErrno set by seekAndRead */
3093 return SQLITE_IOERR_READ;
3094 }else{
dan08da86a2009-08-21 17:18:03 +00003095 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003096 /* Unread parts of the buffer must be zero-filled */
3097 memset(&((char*)pBuf)[got], 0, amt-got);
3098 return SQLITE_IOERR_SHORT_READ;
3099 }
3100}
3101
3102/*
3103** Seek to the offset in id->offset then read cnt bytes into pBuf.
3104** Return the number of bytes actually read. Update the offset.
3105**
3106** To avoid stomping the errno value on a failed write the lastErrno value
3107** is set before returning.
3108*/
3109static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3110 int got;
drh7ed97b92010-01-20 13:07:21 +00003111#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003112 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003113#endif
drhc1fd2cf2012-10-01 12:16:26 +00003114 assert( cnt==(cnt&0x1ffff) );
3115 cnt &= 0x1ffff;
drh734c9862008-11-28 15:37:20 +00003116 TIMER_START;
3117#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003118 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003119#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003120 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003121#else
drhbd1e50c2011-08-19 14:54:12 +00003122 do{
3123 newOffset = lseek(id->h, offset, SEEK_SET);
3124 SimulateIOError( newOffset-- );
3125 if( newOffset!=offset ){
3126 if( newOffset == -1 ){
3127 ((unixFile*)id)->lastErrno = errno;
3128 }else{
drhf2f105d2012-08-20 15:53:54 +00003129 ((unixFile*)id)->lastErrno = 0;
drhbd1e50c2011-08-19 14:54:12 +00003130 }
3131 return -1;
drh734c9862008-11-28 15:37:20 +00003132 }
drhbd1e50c2011-08-19 14:54:12 +00003133 got = osWrite(id->h, pBuf, cnt);
3134 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003135#endif
3136 TIMER_END;
3137 if( got<0 ){
3138 ((unixFile*)id)->lastErrno = errno;
3139 }
3140
drh308c2a52010-05-14 11:30:18 +00003141 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003142 return got;
3143}
3144
3145
3146/*
3147** Write data from a buffer into a file. Return SQLITE_OK on success
3148** or some other error code on failure.
3149*/
3150static int unixWrite(
3151 sqlite3_file *id,
3152 const void *pBuf,
3153 int amt,
3154 sqlite3_int64 offset
3155){
dan08da86a2009-08-21 17:18:03 +00003156 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003157 int wrote = 0;
3158 assert( id );
3159 assert( amt>0 );
dan6101d502013-03-22 08:58:38 +00003160 assert( offset>=pFile->mmapSize ); /* Never write into the mmapped region */
drh8f941bc2009-01-14 23:03:40 +00003161
dan08da86a2009-08-21 17:18:03 +00003162 /* If this is a database file (not a journal, master-journal or temp
3163 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003164#if 0
dane946c392009-08-22 11:39:46 +00003165 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003166 || offset>=PENDING_BYTE+512
3167 || offset+amt<=PENDING_BYTE
3168 );
dan7c246102010-04-12 19:00:29 +00003169#endif
drh08c6d442009-02-09 17:34:07 +00003170
drhd3d8c042012-05-29 17:02:40 +00003171#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003172 /* If we are doing a normal write to a database file (as opposed to
3173 ** doing a hot-journal rollback or a write to some file other than a
3174 ** normal database file) then record the fact that the database
3175 ** has changed. If the transaction counter is modified, record that
3176 ** fact too.
3177 */
dan08da86a2009-08-21 17:18:03 +00003178 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003179 pFile->dbUpdate = 1; /* The database has been modified */
3180 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003181 int rc;
drh8f941bc2009-01-14 23:03:40 +00003182 char oldCntr[4];
3183 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003184 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003185 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003186 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003187 pFile->transCntrChng = 1; /* The transaction counter has changed */
3188 }
3189 }
3190 }
3191#endif
3192
dan08da86a2009-08-21 17:18:03 +00003193 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003194 amt -= wrote;
3195 offset += wrote;
3196 pBuf = &((char*)pBuf)[wrote];
3197 }
3198 SimulateIOError(( wrote=(-1), amt=1 ));
3199 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003200
drh734c9862008-11-28 15:37:20 +00003201 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003202 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003203 /* lastErrno set by seekAndWrite */
3204 return SQLITE_IOERR_WRITE;
3205 }else{
dan08da86a2009-08-21 17:18:03 +00003206 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003207 return SQLITE_FULL;
3208 }
3209 }
dan6e09d692010-07-27 18:34:15 +00003210
drh734c9862008-11-28 15:37:20 +00003211 return SQLITE_OK;
3212}
3213
3214#ifdef SQLITE_TEST
3215/*
3216** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003217** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003218*/
3219int sqlite3_sync_count = 0;
3220int sqlite3_fullsync_count = 0;
3221#endif
3222
3223/*
drh89240432009-03-25 01:06:01 +00003224** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003225** Others do no. To be safe, we will stick with the (slightly slower)
3226** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003227** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003228*/
drh20f8e132011-08-31 21:01:55 +00003229#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003230# define fdatasync fsync
3231#endif
3232
3233/*
3234** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3235** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3236** only available on Mac OS X. But that could change.
3237*/
3238#ifdef F_FULLFSYNC
3239# define HAVE_FULLFSYNC 1
3240#else
3241# define HAVE_FULLFSYNC 0
3242#endif
3243
3244
3245/*
3246** The fsync() system call does not work as advertised on many
3247** unix systems. The following procedure is an attempt to make
3248** it work better.
3249**
3250** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3251** for testing when we want to run through the test suite quickly.
3252** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3253** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3254** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003255**
3256** SQLite sets the dataOnly flag if the size of the file is unchanged.
3257** The idea behind dataOnly is that it should only write the file content
3258** to disk, not the inode. We only set dataOnly if the file size is
3259** unchanged since the file size is part of the inode. However,
3260** Ted Ts'o tells us that fdatasync() will also write the inode if the
3261** file size has changed. The only real difference between fdatasync()
3262** and fsync(), Ted tells us, is that fdatasync() will not flush the
3263** inode if the mtime or owner or other inode attributes have changed.
3264** We only care about the file size, not the other file attributes, so
3265** as far as SQLite is concerned, an fdatasync() is always adequate.
3266** So, we always use fdatasync() if it is available, regardless of
3267** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003268*/
3269static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003270 int rc;
drh734c9862008-11-28 15:37:20 +00003271
3272 /* The following "ifdef/elif/else/" block has the same structure as
3273 ** the one below. It is replicated here solely to avoid cluttering
3274 ** up the real code with the UNUSED_PARAMETER() macros.
3275 */
3276#ifdef SQLITE_NO_SYNC
3277 UNUSED_PARAMETER(fd);
3278 UNUSED_PARAMETER(fullSync);
3279 UNUSED_PARAMETER(dataOnly);
3280#elif HAVE_FULLFSYNC
3281 UNUSED_PARAMETER(dataOnly);
3282#else
3283 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003284 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003285#endif
3286
3287 /* Record the number of times that we do a normal fsync() and
3288 ** FULLSYNC. This is used during testing to verify that this procedure
3289 ** gets called with the correct arguments.
3290 */
3291#ifdef SQLITE_TEST
3292 if( fullSync ) sqlite3_fullsync_count++;
3293 sqlite3_sync_count++;
3294#endif
3295
3296 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3297 ** no-op
3298 */
3299#ifdef SQLITE_NO_SYNC
3300 rc = SQLITE_OK;
3301#elif HAVE_FULLFSYNC
3302 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003303 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003304 }else{
3305 rc = 1;
3306 }
3307 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003308 ** It shouldn't be possible for fullfsync to fail on the local
3309 ** file system (on OSX), so failure indicates that FULLFSYNC
3310 ** isn't supported for this file system. So, attempt an fsync
3311 ** and (for now) ignore the overhead of a superfluous fcntl call.
3312 ** It'd be better to detect fullfsync support once and avoid
3313 ** the fcntl call every time sync is called.
3314 */
drh734c9862008-11-28 15:37:20 +00003315 if( rc ) rc = fsync(fd);
3316
drh7ed97b92010-01-20 13:07:21 +00003317#elif defined(__APPLE__)
3318 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3319 ** so currently we default to the macro that redefines fdatasync to fsync
3320 */
3321 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003322#else
drh0b647ff2009-03-21 14:41:04 +00003323 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003324#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003325 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003326 rc = fsync(fd);
3327 }
drh0b647ff2009-03-21 14:41:04 +00003328#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003329#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3330
3331 if( OS_VXWORKS && rc!= -1 ){
3332 rc = 0;
3333 }
chw97185482008-11-17 08:05:31 +00003334 return rc;
drhbfe66312006-10-03 17:40:40 +00003335}
3336
drh734c9862008-11-28 15:37:20 +00003337/*
drh0059eae2011-08-08 23:48:40 +00003338** Open a file descriptor to the directory containing file zFilename.
3339** If successful, *pFd is set to the opened file descriptor and
3340** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3341** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3342** value.
3343**
drh90315a22011-08-10 01:52:12 +00003344** The directory file descriptor is used for only one thing - to
3345** fsync() a directory to make sure file creation and deletion events
3346** are flushed to disk. Such fsyncs are not needed on newer
3347** journaling filesystems, but are required on older filesystems.
3348**
3349** This routine can be overridden using the xSetSysCall interface.
3350** The ability to override this routine was added in support of the
3351** chromium sandbox. Opening a directory is a security risk (we are
3352** told) so making it overrideable allows the chromium sandbox to
3353** replace this routine with a harmless no-op. To make this routine
3354** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3355** *pFd set to a negative number.
3356**
drh0059eae2011-08-08 23:48:40 +00003357** If SQLITE_OK is returned, the caller is responsible for closing
3358** the file descriptor *pFd using close().
3359*/
3360static int openDirectory(const char *zFilename, int *pFd){
3361 int ii;
3362 int fd = -1;
3363 char zDirname[MAX_PATHNAME+1];
3364
3365 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3366 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3367 if( ii>0 ){
3368 zDirname[ii] = '\0';
3369 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3370 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003371 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3372 }
3373 }
3374 *pFd = fd;
3375 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3376}
3377
3378/*
drh734c9862008-11-28 15:37:20 +00003379** Make sure all writes to a particular file are committed to disk.
3380**
3381** If dataOnly==0 then both the file itself and its metadata (file
3382** size, access time, etc) are synced. If dataOnly!=0 then only the
3383** file data is synced.
3384**
3385** Under Unix, also make sure that the directory entry for the file
3386** has been created by fsync-ing the directory that contains the file.
3387** If we do not do this and we encounter a power failure, the directory
3388** entry for the journal might not exist after we reboot. The next
3389** SQLite to access the file will not know that the journal exists (because
3390** the directory entry for the journal was never created) and the transaction
3391** will not roll back - possibly leading to database corruption.
3392*/
3393static int unixSync(sqlite3_file *id, int flags){
3394 int rc;
3395 unixFile *pFile = (unixFile*)id;
3396
3397 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3398 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3399
3400 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3401 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3402 || (flags&0x0F)==SQLITE_SYNC_FULL
3403 );
3404
3405 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3406 ** line is to test that doing so does not cause any problems.
3407 */
3408 SimulateDiskfullError( return SQLITE_FULL );
3409
3410 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003411 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003412 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3413 SimulateIOError( rc=1 );
3414 if( rc ){
3415 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003416 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003417 }
drh0059eae2011-08-08 23:48:40 +00003418
3419 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003420 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3421 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003422 */
3423 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3424 int dirfd;
3425 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003426 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003427 rc = osOpenDirectory(pFile->zPath, &dirfd);
3428 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003429 full_fsync(dirfd, 0, 0);
3430 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003431 }else if( rc==SQLITE_CANTOPEN ){
3432 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003433 }
drh0059eae2011-08-08 23:48:40 +00003434 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003435 }
3436 return rc;
3437}
3438
3439/*
3440** Truncate an open file to a specified size
3441*/
3442static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003443 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003444 int rc;
dan6e09d692010-07-27 18:34:15 +00003445 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003446 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003447
3448 /* If the user has configured a chunk-size for this file, truncate the
3449 ** file so that it consists of an integer number of chunks (i.e. the
3450 ** actual file size after the operation may be larger than the requested
3451 ** size).
3452 */
drhb8af4b72012-04-05 20:04:39 +00003453 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003454 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3455 }
3456
drhff812312011-02-23 13:33:46 +00003457 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003458 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003459 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003460 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003461 }else{
drhd3d8c042012-05-29 17:02:40 +00003462#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003463 /* If we are doing a normal write to a database file (as opposed to
3464 ** doing a hot-journal rollback or a write to some file other than a
3465 ** normal database file) and we truncate the file to zero length,
3466 ** that effectively updates the change counter. This might happen
3467 ** when restoring a database using the backup API from a zero-length
3468 ** source.
3469 */
dan6e09d692010-07-27 18:34:15 +00003470 if( pFile->inNormalWrite && nByte==0 ){
3471 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003472 }
3473#endif
3474
drh734c9862008-11-28 15:37:20 +00003475 return SQLITE_OK;
3476 }
3477}
3478
3479/*
3480** Determine the current size of a file in bytes
3481*/
3482static int unixFileSize(sqlite3_file *id, i64 *pSize){
3483 int rc;
3484 struct stat buf;
3485 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003486 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003487 SimulateIOError( rc=1 );
3488 if( rc!=0 ){
3489 ((unixFile*)id)->lastErrno = errno;
3490 return SQLITE_IOERR_FSTAT;
3491 }
3492 *pSize = buf.st_size;
3493
drh8af6c222010-05-14 12:43:01 +00003494 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003495 ** writes a single byte into that file in order to work around a bug
3496 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3497 ** layers, we need to report this file size as zero even though it is
3498 ** really 1. Ticket #3260.
3499 */
3500 if( *pSize==1 ) *pSize = 0;
3501
3502
3503 return SQLITE_OK;
3504}
3505
drhd2cb50b2009-01-09 21:41:17 +00003506#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003507/*
3508** Handler for proxy-locking file-control verbs. Defined below in the
3509** proxying locking division.
3510*/
3511static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003512#endif
drh715ff302008-12-03 22:32:44 +00003513
dan502019c2010-07-28 14:26:17 +00003514/*
3515** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003516** file-control operation. Enlarge the database to nBytes in size
3517** (rounded up to the next chunk-size). If the database is already
3518** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003519*/
3520static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003521 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003522 i64 nSize; /* Required file size */
3523 struct stat buf; /* Used to hold return values of fstat() */
3524
drh99ab3b12011-03-02 15:09:07 +00003525 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003526
3527 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3528 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003529
dan502019c2010-07-28 14:26:17 +00003530#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003531 /* The code below is handling the return value of osFallocate()
3532 ** correctly. posix_fallocate() is defined to "returns zero on success,
3533 ** or an error number on failure". See the manpage for details. */
3534 int err;
drhff812312011-02-23 13:33:46 +00003535 do{
dan661d71a2011-03-30 19:08:03 +00003536 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3537 }while( err==EINTR );
3538 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003539#else
3540 /* If the OS does not have posix_fallocate(), fake it. First use
3541 ** ftruncate() to set the file size, then write a single byte to
3542 ** the last byte in each block within the extended region. This
3543 ** is the same technique used by glibc to implement posix_fallocate()
3544 ** on systems that do not have a real fallocate() system call.
3545 */
3546 int nBlk = buf.st_blksize; /* File-system block size */
3547 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003548
drhff812312011-02-23 13:33:46 +00003549 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003550 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003551 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003552 }
3553 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003554 while( iWrite<nSize ){
3555 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3556 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003557 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003558 }
dan502019c2010-07-28 14:26:17 +00003559#endif
3560 }
3561 }
3562
3563 return SQLITE_OK;
3564}
danielk1977ad94b582007-08-20 06:44:22 +00003565
danielk1977e3026632004-06-22 11:29:02 +00003566/*
drhf12b3f62011-12-21 14:42:29 +00003567** If *pArg is inititially negative then this is a query. Set *pArg to
3568** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3569**
3570** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3571*/
3572static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3573 if( *pArg<0 ){
3574 *pArg = (pFile->ctrlFlags & mask)!=0;
3575 }else if( (*pArg)==0 ){
3576 pFile->ctrlFlags &= ~mask;
3577 }else{
3578 pFile->ctrlFlags |= mask;
3579 }
3580}
3581
drh696b33e2012-12-06 19:01:42 +00003582/* Forward declaration */
3583static int unixGetTempname(int nBuf, char *zBuf);
3584
drhf12b3f62011-12-21 14:42:29 +00003585/*
drh9e33c2c2007-08-31 18:34:59 +00003586** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003587*/
drhcc6bb3e2007-08-31 16:11:35 +00003588static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003589 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003590 switch( op ){
3591 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003592 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003593 return SQLITE_OK;
3594 }
drh7708e972008-11-29 00:56:52 +00003595 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003596 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003597 return SQLITE_OK;
3598 }
dan6e09d692010-07-27 18:34:15 +00003599 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003600 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003601 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003602 }
drh9ff27ec2010-05-19 19:26:05 +00003603 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003604 int rc;
3605 SimulateIOErrorBenign(1);
3606 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3607 SimulateIOErrorBenign(0);
3608 return rc;
drhf0b190d2011-07-26 16:03:07 +00003609 }
3610 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003611 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3612 return SQLITE_OK;
3613 }
drhcb15f352011-12-23 01:04:17 +00003614 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3615 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003616 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003617 }
drhde60fc22011-12-14 17:53:36 +00003618 case SQLITE_FCNTL_VFSNAME: {
3619 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3620 return SQLITE_OK;
3621 }
drh696b33e2012-12-06 19:01:42 +00003622 case SQLITE_FCNTL_TEMPFILENAME: {
3623 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3624 if( zTFile ){
3625 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3626 *(char**)pArg = zTFile;
3627 }
3628 return SQLITE_OK;
3629 }
danb2d3de32013-03-14 18:34:37 +00003630 case SQLITE_FCNTL_GETFD: {
3631 *(int*)pArg = pFile->h;
3632 return SQLITE_OK;
3633 }
drhd3d8c042012-05-29 17:02:40 +00003634#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003635 /* The pager calls this method to signal that it has done
3636 ** a rollback and that the database is therefore unchanged and
3637 ** it hence it is OK for the transaction change counter to be
3638 ** unchanged.
3639 */
3640 case SQLITE_FCNTL_DB_UNCHANGED: {
3641 ((unixFile*)id)->dbUpdate = 0;
3642 return SQLITE_OK;
3643 }
3644#endif
drhd2cb50b2009-01-09 21:41:17 +00003645#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003646 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003647 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003648 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003649 }
drhd2cb50b2009-01-09 21:41:17 +00003650#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003651 }
drh0b52b7d2011-01-26 19:46:22 +00003652 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003653}
3654
3655/*
danielk1977a3d4c882007-03-23 10:08:38 +00003656** Return the sector size in bytes of the underlying block device for
3657** the specified file. This is almost always 512 bytes, but may be
3658** larger for some devices.
3659**
3660** SQLite code assumes this function cannot fail. It also assumes that
3661** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003662** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003663** same for both.
3664*/
drh537dddf2012-10-26 13:46:24 +00003665#ifndef __QNXNTO__
3666static int unixSectorSize(sqlite3_file *NotUsed){
3667 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003668 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003669}
drh537dddf2012-10-26 13:46:24 +00003670#endif
3671
3672/*
3673** The following version of unixSectorSize() is optimized for QNX.
3674*/
3675#ifdef __QNXNTO__
3676#include <sys/dcmd_blk.h>
3677#include <sys/statvfs.h>
3678static int unixSectorSize(sqlite3_file *id){
3679 unixFile *pFile = (unixFile*)id;
3680 if( pFile->sectorSize == 0 ){
3681 struct statvfs fsInfo;
3682
3683 /* Set defaults for non-supported filesystems */
3684 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3685 pFile->deviceCharacteristics = 0;
3686 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3687 return pFile->sectorSize;
3688 }
3689
3690 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3691 pFile->sectorSize = fsInfo.f_bsize;
3692 pFile->deviceCharacteristics =
3693 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3694 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3695 ** the write succeeds */
3696 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3697 ** so it is ordered */
3698 0;
3699 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3700 pFile->sectorSize = fsInfo.f_bsize;
3701 pFile->deviceCharacteristics =
3702 /* etfs cluster size writes are atomic */
3703 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3704 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3705 ** the write succeeds */
3706 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3707 ** so it is ordered */
3708 0;
3709 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3710 pFile->sectorSize = fsInfo.f_bsize;
3711 pFile->deviceCharacteristics =
3712 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3713 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3714 ** the write succeeds */
3715 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3716 ** so it is ordered */
3717 0;
3718 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3719 pFile->sectorSize = fsInfo.f_bsize;
3720 pFile->deviceCharacteristics =
3721 /* full bitset of atomics from max sector size and smaller */
3722 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3723 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3724 ** so it is ordered */
3725 0;
3726 }else if( strstr(fsInfo.f_basetype, "dos") ){
3727 pFile->sectorSize = fsInfo.f_bsize;
3728 pFile->deviceCharacteristics =
3729 /* full bitset of atomics from max sector size and smaller */
3730 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3731 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3732 ** so it is ordered */
3733 0;
3734 }else{
3735 pFile->deviceCharacteristics =
3736 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3737 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3738 ** the write succeeds */
3739 0;
3740 }
3741 }
3742 /* Last chance verification. If the sector size isn't a multiple of 512
3743 ** then it isn't valid.*/
3744 if( pFile->sectorSize % 512 != 0 ){
3745 pFile->deviceCharacteristics = 0;
3746 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3747 }
3748 return pFile->sectorSize;
3749}
3750#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003751
danielk197790949c22007-08-17 16:50:38 +00003752/*
drhf12b3f62011-12-21 14:42:29 +00003753** Return the device characteristics for the file.
3754**
drhcb15f352011-12-23 01:04:17 +00003755** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3756** However, that choice is contraversial since technically the underlying
3757** file system does not always provide powersafe overwrites. (In other
3758** words, after a power-loss event, parts of the file that were never
3759** written might end up being altered.) However, non-PSOW behavior is very,
3760** very rare. And asserting PSOW makes a large reduction in the amount
3761** of required I/O for journaling, since a lot of padding is eliminated.
3762** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3763** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003764*/
drhf12b3f62011-12-21 14:42:29 +00003765static int unixDeviceCharacteristics(sqlite3_file *id){
3766 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003767 int rc = 0;
3768#ifdef __QNXNTO__
3769 if( p->sectorSize==0 ) unixSectorSize(id);
3770 rc = p->deviceCharacteristics;
3771#endif
drhcb15f352011-12-23 01:04:17 +00003772 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003773 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003774 }
drh537dddf2012-10-26 13:46:24 +00003775 return rc;
danielk197762079062007-08-15 17:08:46 +00003776}
3777
drhd9e5c4f2010-05-12 18:01:39 +00003778#ifndef SQLITE_OMIT_WAL
3779
3780
3781/*
drhd91c68f2010-05-14 14:52:25 +00003782** Object used to represent an shared memory buffer.
3783**
3784** When multiple threads all reference the same wal-index, each thread
3785** has its own unixShm object, but they all point to a single instance
3786** of this unixShmNode object. In other words, each wal-index is opened
3787** only once per process.
3788**
3789** Each unixShmNode object is connected to a single unixInodeInfo object.
3790** We could coalesce this object into unixInodeInfo, but that would mean
3791** every open file that does not use shared memory (in other words, most
3792** open files) would have to carry around this extra information. So
3793** the unixInodeInfo object contains a pointer to this unixShmNode object
3794** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003795**
3796** unixMutexHeld() must be true when creating or destroying
3797** this object or while reading or writing the following fields:
3798**
3799** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003800**
3801** The following fields are read-only after the object is created:
3802**
3803** fid
3804** zFilename
3805**
drhd91c68f2010-05-14 14:52:25 +00003806** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003807** unixMutexHeld() is true when reading or writing any other field
3808** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003809*/
drhd91c68f2010-05-14 14:52:25 +00003810struct unixShmNode {
3811 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003812 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003813 char *zFilename; /* Name of the mmapped file */
3814 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003815 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003816 u16 nRegion; /* Size of array apRegion */
3817 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003818 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003819 int nRef; /* Number of unixShm objects pointing to this */
3820 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003821#ifdef SQLITE_DEBUG
3822 u8 exclMask; /* Mask of exclusive locks held */
3823 u8 sharedMask; /* Mask of shared locks held */
3824 u8 nextShmId; /* Next available unixShm.id value */
3825#endif
3826};
3827
3828/*
drhd9e5c4f2010-05-12 18:01:39 +00003829** Structure used internally by this VFS to record the state of an
3830** open shared memory connection.
3831**
drhd91c68f2010-05-14 14:52:25 +00003832** The following fields are initialized when this object is created and
3833** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003834**
drhd91c68f2010-05-14 14:52:25 +00003835** unixShm.pFile
3836** unixShm.id
3837**
3838** All other fields are read/write. The unixShm.pFile->mutex must be held
3839** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003840*/
3841struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003842 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3843 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003844 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003845 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003846 u16 sharedMask; /* Mask of shared locks held */
3847 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003848};
3849
3850/*
drhd9e5c4f2010-05-12 18:01:39 +00003851** Constants used for locking
3852*/
drhbd9676c2010-06-23 17:58:38 +00003853#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003854#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003855
drhd9e5c4f2010-05-12 18:01:39 +00003856/*
drh73b64e42010-05-30 19:55:15 +00003857** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003858**
3859** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3860** otherwise.
3861*/
3862static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003863 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3864 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003865 int ofst, /* First byte of the locking range */
3866 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003867){
3868 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003869 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003870
drhd91c68f2010-05-14 14:52:25 +00003871 /* Access to the unixShmNode object is serialized by the caller */
3872 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003873
drh73b64e42010-05-30 19:55:15 +00003874 /* Shared locks never span more than one byte */
3875 assert( n==1 || lockType!=F_RDLCK );
3876
3877 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003878 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003879
drh3cb93392011-03-12 18:10:44 +00003880 if( pShmNode->h>=0 ){
3881 /* Initialize the locking parameters */
3882 memset(&f, 0, sizeof(f));
3883 f.l_type = lockType;
3884 f.l_whence = SEEK_SET;
3885 f.l_start = ofst;
3886 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003887
drh3cb93392011-03-12 18:10:44 +00003888 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3889 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3890 }
drhd9e5c4f2010-05-12 18:01:39 +00003891
3892 /* Update the global lock state and do debug tracing */
3893#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003894 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003895 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003896 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003897 if( rc==SQLITE_OK ){
3898 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003899 OSTRACE(("unlock %d ok", ofst));
3900 pShmNode->exclMask &= ~mask;
3901 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003902 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003903 OSTRACE(("read-lock %d ok", ofst));
3904 pShmNode->exclMask &= ~mask;
3905 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003906 }else{
3907 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003908 OSTRACE(("write-lock %d ok", ofst));
3909 pShmNode->exclMask |= mask;
3910 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003911 }
3912 }else{
3913 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003914 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003915 }else if( lockType==F_RDLCK ){
3916 OSTRACE(("read-lock failed"));
3917 }else{
3918 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003919 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003920 }
3921 }
drh20e1f082010-05-31 16:10:12 +00003922 OSTRACE((" - afterwards %03x,%03x\n",
3923 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003924 }
drhd9e5c4f2010-05-12 18:01:39 +00003925#endif
3926
3927 return rc;
3928}
3929
drhd9e5c4f2010-05-12 18:01:39 +00003930
3931/*
drhd91c68f2010-05-14 14:52:25 +00003932** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003933**
3934** This is not a VFS shared-memory method; it is a utility function called
3935** by VFS shared-memory methods.
3936*/
drhd91c68f2010-05-14 14:52:25 +00003937static void unixShmPurge(unixFile *pFd){
3938 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003939 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003940 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003941 int i;
drhd91c68f2010-05-14 14:52:25 +00003942 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003943 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003944 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003945 if( p->h>=0 ){
3946 munmap(p->apRegion[i], p->szRegion);
3947 }else{
3948 sqlite3_free(p->apRegion[i]);
3949 }
dan13a3cb82010-06-11 19:04:21 +00003950 }
dan18801912010-06-14 14:07:50 +00003951 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003952 if( p->h>=0 ){
3953 robust_close(pFd, p->h, __LINE__);
3954 p->h = -1;
3955 }
drhd91c68f2010-05-14 14:52:25 +00003956 p->pInode->pShmNode = 0;
3957 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003958 }
3959}
3960
3961/*
danda9fe0c2010-07-13 18:44:03 +00003962** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003963** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003964**
drh7234c6d2010-06-19 15:10:09 +00003965** The file used to implement shared-memory is in the same directory
3966** as the open database file and has the same name as the open database
3967** file with the "-shm" suffix added. For example, if the database file
3968** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003969** for shared memory will be called "/home/user1/config.db-shm".
3970**
3971** Another approach to is to use files in /dev/shm or /dev/tmp or an
3972** some other tmpfs mount. But if a file in a different directory
3973** from the database file is used, then differing access permissions
3974** or a chroot() might cause two different processes on the same
3975** database to end up using different files for shared memory -
3976** meaning that their memory would not really be shared - resulting
3977** in database corruption. Nevertheless, this tmpfs file usage
3978** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3979** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3980** option results in an incompatible build of SQLite; builds of SQLite
3981** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3982** same database file at the same time, database corruption will likely
3983** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3984** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003985**
3986** When opening a new shared-memory file, if no other instances of that
3987** file are currently open, in this process or in other processes, then
3988** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003989**
3990** If the original database file (pDbFd) is using the "unix-excl" VFS
3991** that means that an exclusive lock is held on the database file and
3992** that no other processes are able to read or write the database. In
3993** that case, we do not really need shared memory. No shared memory
3994** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003995*/
danda9fe0c2010-07-13 18:44:03 +00003996static int unixOpenSharedMemory(unixFile *pDbFd){
3997 struct unixShm *p = 0; /* The connection to be opened */
3998 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3999 int rc; /* Result code */
4000 unixInodeInfo *pInode; /* The inode of fd */
4001 char *zShmFilename; /* Name of the file used for SHM */
4002 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004003
danda9fe0c2010-07-13 18:44:03 +00004004 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004005 p = sqlite3_malloc( sizeof(*p) );
4006 if( p==0 ) return SQLITE_NOMEM;
4007 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004008 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004009
danda9fe0c2010-07-13 18:44:03 +00004010 /* Check to see if a unixShmNode object already exists. Reuse an existing
4011 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004012 */
4013 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004014 pInode = pDbFd->pInode;
4015 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004016 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004017 struct stat sStat; /* fstat() info for database file */
4018
4019 /* Call fstat() to figure out the permissions on the database file. If
4020 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004021 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004022 */
drh3cb93392011-03-12 18:10:44 +00004023 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004024 rc = SQLITE_IOERR_FSTAT;
4025 goto shm_open_err;
4026 }
4027
drha4ced192010-07-15 18:32:40 +00004028#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004029 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004030#else
drh52bcde02012-01-03 14:50:45 +00004031 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004032#endif
drh7234c6d2010-06-19 15:10:09 +00004033 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004034 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004035 rc = SQLITE_NOMEM;
4036 goto shm_open_err;
4037 }
drh9cb5a0d2012-01-05 21:19:54 +00004038 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004039 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004040#ifdef SQLITE_SHM_DIRECTORY
4041 sqlite3_snprintf(nShmFilename, zShmFilename,
4042 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4043 (u32)sStat.st_ino, (u32)sStat.st_dev);
4044#else
drh7234c6d2010-06-19 15:10:09 +00004045 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004046 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004047#endif
drhd91c68f2010-05-14 14:52:25 +00004048 pShmNode->h = -1;
4049 pDbFd->pInode->pShmNode = pShmNode;
4050 pShmNode->pInode = pDbFd->pInode;
4051 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4052 if( pShmNode->mutex==0 ){
4053 rc = SQLITE_NOMEM;
4054 goto shm_open_err;
4055 }
drhd9e5c4f2010-05-12 18:01:39 +00004056
drh3cb93392011-03-12 18:10:44 +00004057 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004058 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004059 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004060 openFlags = O_RDONLY;
4061 pShmNode->isReadonly = 1;
4062 }
4063 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004064 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004065 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4066 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004067 }
drhac7c3ac2012-02-11 19:23:48 +00004068
4069 /* If this process is running as root, make sure that the SHM file
4070 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004071 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004072 */
drhed466822012-05-31 13:10:49 +00004073 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004074
4075 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004076 ** If not, truncate the file to zero length.
4077 */
4078 rc = SQLITE_OK;
4079 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4080 if( robust_ftruncate(pShmNode->h, 0) ){
4081 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004082 }
4083 }
drh66dfec8b2011-06-01 20:01:49 +00004084 if( rc==SQLITE_OK ){
4085 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4086 }
4087 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004088 }
drhd9e5c4f2010-05-12 18:01:39 +00004089 }
4090
drhd91c68f2010-05-14 14:52:25 +00004091 /* Make the new connection a child of the unixShmNode */
4092 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004093#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004094 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004095#endif
drhd91c68f2010-05-14 14:52:25 +00004096 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004097 pDbFd->pShm = p;
4098 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004099
4100 /* The reference count on pShmNode has already been incremented under
4101 ** the cover of the unixEnterMutex() mutex and the pointer from the
4102 ** new (struct unixShm) object to the pShmNode has been set. All that is
4103 ** left to do is to link the new object into the linked list starting
4104 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4105 ** mutex.
4106 */
4107 sqlite3_mutex_enter(pShmNode->mutex);
4108 p->pNext = pShmNode->pFirst;
4109 pShmNode->pFirst = p;
4110 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004111 return SQLITE_OK;
4112
4113 /* Jump here on any error */
4114shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004115 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004116 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004117 unixLeaveMutex();
4118 return rc;
4119}
4120
4121/*
danda9fe0c2010-07-13 18:44:03 +00004122** This function is called to obtain a pointer to region iRegion of the
4123** shared-memory associated with the database file fd. Shared-memory regions
4124** are numbered starting from zero. Each shared-memory region is szRegion
4125** bytes in size.
4126**
4127** If an error occurs, an error code is returned and *pp is set to NULL.
4128**
4129** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4130** region has not been allocated (by any client, including one running in a
4131** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4132** bExtend is non-zero and the requested shared-memory region has not yet
4133** been allocated, it is allocated by this function.
4134**
4135** If the shared-memory region has already been allocated or is allocated by
4136** this call as described above, then it is mapped into this processes
4137** address space (if it is not already), *pp is set to point to the mapped
4138** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004139*/
danda9fe0c2010-07-13 18:44:03 +00004140static int unixShmMap(
4141 sqlite3_file *fd, /* Handle open on database file */
4142 int iRegion, /* Region to retrieve */
4143 int szRegion, /* Size of regions */
4144 int bExtend, /* True to extend file if necessary */
4145 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004146){
danda9fe0c2010-07-13 18:44:03 +00004147 unixFile *pDbFd = (unixFile*)fd;
4148 unixShm *p;
4149 unixShmNode *pShmNode;
4150 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004151
danda9fe0c2010-07-13 18:44:03 +00004152 /* If the shared-memory file has not yet been opened, open it now. */
4153 if( pDbFd->pShm==0 ){
4154 rc = unixOpenSharedMemory(pDbFd);
4155 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004156 }
drhd9e5c4f2010-05-12 18:01:39 +00004157
danda9fe0c2010-07-13 18:44:03 +00004158 p = pDbFd->pShm;
4159 pShmNode = p->pShmNode;
4160 sqlite3_mutex_enter(pShmNode->mutex);
4161 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004162 assert( pShmNode->pInode==pDbFd->pInode );
4163 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4164 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004165
4166 if( pShmNode->nRegion<=iRegion ){
4167 char **apNew; /* New apRegion[] array */
4168 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4169 struct stat sStat; /* Used by fstat() */
4170
4171 pShmNode->szRegion = szRegion;
4172
drh3cb93392011-03-12 18:10:44 +00004173 if( pShmNode->h>=0 ){
4174 /* The requested region is not mapped into this processes address space.
4175 ** Check to see if it has been allocated (i.e. if the wal-index file is
4176 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004177 */
drh3cb93392011-03-12 18:10:44 +00004178 if( osFstat(pShmNode->h, &sStat) ){
4179 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004180 goto shmpage_out;
4181 }
drh3cb93392011-03-12 18:10:44 +00004182
4183 if( sStat.st_size<nByte ){
4184 /* The requested memory region does not exist. If bExtend is set to
4185 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4186 **
4187 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4188 ** the requested memory region.
4189 */
4190 if( !bExtend ) goto shmpage_out;
drh0fbb50e2012-11-13 10:54:12 +00004191#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
4192 if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
4193 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
4194 pShmNode->zFilename);
4195 goto shmpage_out;
4196 }
4197#else
drh3cb93392011-03-12 18:10:44 +00004198 if( robust_ftruncate(pShmNode->h, nByte) ){
4199 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4200 pShmNode->zFilename);
4201 goto shmpage_out;
4202 }
drh0fbb50e2012-11-13 10:54:12 +00004203#endif
drh3cb93392011-03-12 18:10:44 +00004204 }
danda9fe0c2010-07-13 18:44:03 +00004205 }
4206
4207 /* Map the requested memory region into this processes address space. */
4208 apNew = (char **)sqlite3_realloc(
4209 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4210 );
4211 if( !apNew ){
4212 rc = SQLITE_IOERR_NOMEM;
4213 goto shmpage_out;
4214 }
4215 pShmNode->apRegion = apNew;
4216 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004217 void *pMem;
4218 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004219 pMem = mmap(0, szRegion,
4220 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004221 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004222 );
4223 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004224 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004225 goto shmpage_out;
4226 }
4227 }else{
4228 pMem = sqlite3_malloc(szRegion);
4229 if( pMem==0 ){
4230 rc = SQLITE_NOMEM;
4231 goto shmpage_out;
4232 }
4233 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004234 }
4235 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4236 pShmNode->nRegion++;
4237 }
4238 }
4239
4240shmpage_out:
4241 if( pShmNode->nRegion>iRegion ){
4242 *pp = pShmNode->apRegion[iRegion];
4243 }else{
4244 *pp = 0;
4245 }
drh66dfec8b2011-06-01 20:01:49 +00004246 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004247 sqlite3_mutex_leave(pShmNode->mutex);
4248 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004249}
4250
4251/*
drhd9e5c4f2010-05-12 18:01:39 +00004252** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004253**
4254** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4255** different here than in posix. In xShmLock(), one can go from unlocked
4256** to shared and back or from unlocked to exclusive and back. But one may
4257** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004258*/
4259static int unixShmLock(
4260 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004261 int ofst, /* First lock to acquire or release */
4262 int n, /* Number of locks to acquire or release */
4263 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004264){
drh73b64e42010-05-30 19:55:15 +00004265 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4266 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4267 unixShm *pX; /* For looping over all siblings */
4268 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4269 int rc = SQLITE_OK; /* Result code */
4270 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004271
drhd91c68f2010-05-14 14:52:25 +00004272 assert( pShmNode==pDbFd->pInode->pShmNode );
4273 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004274 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004275 assert( n>=1 );
4276 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4277 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4278 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4279 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4280 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004281 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4282 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004283
drhc99597c2010-05-31 01:41:15 +00004284 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004285 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004286 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004287 if( flags & SQLITE_SHM_UNLOCK ){
4288 u16 allMask = 0; /* Mask of locks held by siblings */
4289
4290 /* See if any siblings hold this same lock */
4291 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4292 if( pX==p ) continue;
4293 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4294 allMask |= pX->sharedMask;
4295 }
4296
4297 /* Unlock the system-level locks */
4298 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004299 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004300 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004301 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004302 }
drh73b64e42010-05-30 19:55:15 +00004303
4304 /* Undo the local locks */
4305 if( rc==SQLITE_OK ){
4306 p->exclMask &= ~mask;
4307 p->sharedMask &= ~mask;
4308 }
4309 }else if( flags & SQLITE_SHM_SHARED ){
4310 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4311
4312 /* Find out which shared locks are already held by sibling connections.
4313 ** If any sibling already holds an exclusive lock, go ahead and return
4314 ** SQLITE_BUSY.
4315 */
4316 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004317 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004318 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004319 break;
4320 }
4321 allShared |= pX->sharedMask;
4322 }
4323
4324 /* Get shared locks at the system level, if necessary */
4325 if( rc==SQLITE_OK ){
4326 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004327 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004328 }else{
drh73b64e42010-05-30 19:55:15 +00004329 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004330 }
drhd9e5c4f2010-05-12 18:01:39 +00004331 }
drh73b64e42010-05-30 19:55:15 +00004332
4333 /* Get the local shared locks */
4334 if( rc==SQLITE_OK ){
4335 p->sharedMask |= mask;
4336 }
4337 }else{
4338 /* Make sure no sibling connections hold locks that will block this
4339 ** lock. If any do, return SQLITE_BUSY right away.
4340 */
4341 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004342 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4343 rc = SQLITE_BUSY;
4344 break;
4345 }
4346 }
4347
4348 /* Get the exclusive locks at the system level. Then if successful
4349 ** also mark the local connection as being locked.
4350 */
4351 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004352 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004353 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004354 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004355 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004356 }
drhd9e5c4f2010-05-12 18:01:39 +00004357 }
4358 }
drhd91c68f2010-05-14 14:52:25 +00004359 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004360 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4361 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004362 return rc;
4363}
4364
drh286a2882010-05-20 23:51:06 +00004365/*
4366** Implement a memory barrier or memory fence on shared memory.
4367**
4368** All loads and stores begun before the barrier must complete before
4369** any load or store begun after the barrier.
4370*/
4371static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004372 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004373){
drhff828942010-06-26 21:34:06 +00004374 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004375 unixEnterMutex();
4376 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004377}
4378
dan18801912010-06-14 14:07:50 +00004379/*
danda9fe0c2010-07-13 18:44:03 +00004380** Close a connection to shared-memory. Delete the underlying
4381** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004382**
4383** If there is no shared memory associated with the connection then this
4384** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004385*/
danda9fe0c2010-07-13 18:44:03 +00004386static int unixShmUnmap(
4387 sqlite3_file *fd, /* The underlying database file */
4388 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004389){
danda9fe0c2010-07-13 18:44:03 +00004390 unixShm *p; /* The connection to be closed */
4391 unixShmNode *pShmNode; /* The underlying shared-memory file */
4392 unixShm **pp; /* For looping over sibling connections */
4393 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004394
danda9fe0c2010-07-13 18:44:03 +00004395 pDbFd = (unixFile*)fd;
4396 p = pDbFd->pShm;
4397 if( p==0 ) return SQLITE_OK;
4398 pShmNode = p->pShmNode;
4399
4400 assert( pShmNode==pDbFd->pInode->pShmNode );
4401 assert( pShmNode->pInode==pDbFd->pInode );
4402
4403 /* Remove connection p from the set of connections associated
4404 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004405 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004406 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4407 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004408
danda9fe0c2010-07-13 18:44:03 +00004409 /* Free the connection p */
4410 sqlite3_free(p);
4411 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004412 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004413
4414 /* If pShmNode->nRef has reached 0, then close the underlying
4415 ** shared-memory file, too */
4416 unixEnterMutex();
4417 assert( pShmNode->nRef>0 );
4418 pShmNode->nRef--;
4419 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004420 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004421 unixShmPurge(pDbFd);
4422 }
4423 unixLeaveMutex();
4424
4425 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004426}
drh286a2882010-05-20 23:51:06 +00004427
danda9fe0c2010-07-13 18:44:03 +00004428
drhd9e5c4f2010-05-12 18:01:39 +00004429#else
drh6b017cc2010-06-14 18:01:46 +00004430# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004431# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004432# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004433# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004434#endif /* #ifndef SQLITE_OMIT_WAL */
4435
drh734c9862008-11-28 15:37:20 +00004436/*
dand306e1a2013-03-20 18:25:49 +00004437** Arguments x and y are both integers. Argument y must be a power of 2.
4438** Round x up to the nearest integer multiple of y. For example:
4439**
4440** ROUNDUP(0, 8) -> 0
4441** ROUNDUP(13, 8) -> 16
4442** ROUNDUP(32, 8) -> 32
4443*/
4444#define ROUNDUP(x,y) (((x)+y-1)&~(y-1))
4445
4446/*
dan5d8a1372013-03-19 19:28:06 +00004447** Map, remap or unmap part of the database file.
4448*/
4449static int unixMremap(
4450 sqlite3_file *fd, /* Main database file */
daneb97b292013-03-20 14:26:59 +00004451 int flags, /* Mask of SQLITE_MREMAP_XXX flags */
dan5d8a1372013-03-19 19:28:06 +00004452 sqlite3_int64 iOff, /* Offset to start mapping at */
4453 sqlite3_int64 nOld, /* Size of old mapping, or zero */
4454 sqlite3_int64 nNew, /* Size of new mapping, or zero */
4455 void **ppMap /* IN/OUT: Old/new mappings */
4456){
4457 unixFile *p = (unixFile *)fd; /* The underlying database file */
4458 int rc = SQLITE_OK; /* Return code */
4459 void *pNew = 0; /* New mapping */
dand306e1a2013-03-20 18:25:49 +00004460 i64 nNewRnd; /* nNew rounded up */
4461 i64 nOldRnd; /* nOld rounded up */
dan5d8a1372013-03-19 19:28:06 +00004462
4463 assert( iOff==0 );
dan6101d502013-03-22 08:58:38 +00004464 assert( p->mmapSize==nOld );
4465 assert( p->pMapRegion==0 || p->pMapRegion==(*ppMap) );
daneb97b292013-03-20 14:26:59 +00004466
4467 /* If the SQLITE_MREMAP_EXTEND flag is set, then the size of the requested
4468 ** mapping (nNew bytes) may be greater than the size of the database file.
4469 ** If this is the case, extend the file on disk using ftruncate(). */
4470 assert( nNew>0 || (flags & SQLITE_MREMAP_EXTEND)==0 );
4471 if( flags & SQLITE_MREMAP_EXTEND ){
4472 struct stat statbuf; /* Low-level file information */
4473 rc = osFstat(p->h, &statbuf);
4474 if( rc==SQLITE_OK && nNew>statbuf.st_size ){
4475 rc = robust_ftruncate(p->h, nNew);
4476 }
4477 if( rc!=SQLITE_OK ) return rc;
4478 }
4479
dand306e1a2013-03-20 18:25:49 +00004480 /* According to some sources, the effect of changing the size of the
4481 ** underlying file on mapped regions that correspond to the added or
4482 ** removed pages is undefined. However, there is reason to believe that
4483 ** on modern platforms like Linux or OSX, things just work. For example,
4484 ** it is possible to create a mapping larger than the file on disk and
4485 ** extend the file on disk later on.
4486 **
danc71b45e2013-03-21 14:47:47 +00004487 ** Exploit this on Linux and OSX to reduce the number of munmap()/mmap()
4488 ** calls required if the file size is changing. In this case all mappings
4489 ** are rounded up to the nearest 4MB. And if a new mapping is requested
4490 ** that has the same rounded size as an old mapping, the old mapping can
4491 ** be reused as is. */
4492#if defined(__APPLE__) || defined(__linux__)
dand306e1a2013-03-20 18:25:49 +00004493 nNewRnd = ROUNDUP(nNew, 4096*1024);
4494 nOldRnd = ROUNDUP(nOld, 4096*1024);
4495#else
4496 nNewRnd = ROUNDUP(nNew, 4096*1);
4497 nOldRnd = ROUNDUP(nOld, 4096*1);
4498#endif
4499
4500 /* On OSX or Linux, reuse the old mapping if it is the right size. */
4501#if defined(__APPLE__) || defined(__linux__)
4502 if( nNewRnd==nOldRnd ){
dan6101d502013-03-22 08:58:38 +00004503 VVA_ONLY( p->mmapSize = nNew; )
dand306e1a2013-03-20 18:25:49 +00004504 return SQLITE_OK;
4505 }
4506#endif
4507
dand306e1a2013-03-20 18:25:49 +00004508 /* If we get this far, unmap any old mapping. */
4509 if( nOldRnd!=0 ){
dan5d8a1372013-03-19 19:28:06 +00004510 void *pOld = *ppMap;
dand306e1a2013-03-20 18:25:49 +00004511 munmap(pOld, nOldRnd);
dan6101d502013-03-22 08:58:38 +00004512 VVA_ONLY( p->mmapSize = 0; p->pMapRegion = 0; );
dan5d8a1372013-03-19 19:28:06 +00004513 }
4514
dand306e1a2013-03-20 18:25:49 +00004515 /* And, if required, use mmap() to create a new mapping. */
4516 if( nNewRnd>0 ){
dan5d8a1372013-03-19 19:28:06 +00004517 int flags = PROT_READ;
4518 if( (p->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
dand306e1a2013-03-20 18:25:49 +00004519 pNew = mmap(0, nNewRnd, flags, MAP_SHARED, p->h, iOff);
dan5d8a1372013-03-19 19:28:06 +00004520 if( pNew==MAP_FAILED ){
4521 pNew = 0;
dan6101d502013-03-22 08:58:38 +00004522 VVA_ONLY( p->mmapSize = 0; p->pMapRegion = 0; )
daneb97b292013-03-20 14:26:59 +00004523 rc = SQLITE_IOERR_MREMAP;
dan6101d502013-03-22 08:58:38 +00004524 }else{
4525 VVA_ONLY( p->mmapSize = nNew; p->pMapRegion = pNew; )
dan5d8a1372013-03-19 19:28:06 +00004526 }
4527 }
4528
4529 *ppMap = pNew;
4530 return rc;
4531}
4532
4533/*
drh734c9862008-11-28 15:37:20 +00004534** Here ends the implementation of all sqlite3_file methods.
4535**
4536********************** End sqlite3_file Methods *******************************
4537******************************************************************************/
4538
4539/*
drh6b9d6dd2008-12-03 19:34:47 +00004540** This division contains definitions of sqlite3_io_methods objects that
4541** implement various file locking strategies. It also contains definitions
4542** of "finder" functions. A finder-function is used to locate the appropriate
4543** sqlite3_io_methods object for a particular database file. The pAppData
4544** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4545** the correct finder-function for that VFS.
4546**
4547** Most finder functions return a pointer to a fixed sqlite3_io_methods
4548** object. The only interesting finder-function is autolockIoFinder, which
4549** looks at the filesystem type and tries to guess the best locking
4550** strategy from that.
4551**
drh1875f7a2008-12-08 18:19:17 +00004552** For finder-funtion F, two objects are created:
4553**
4554** (1) The real finder-function named "FImpt()".
4555**
dane946c392009-08-22 11:39:46 +00004556** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004557**
4558**
4559** A pointer to the F pointer is used as the pAppData value for VFS
4560** objects. We have to do this instead of letting pAppData point
4561** directly at the finder-function since C90 rules prevent a void*
4562** from be cast into a function pointer.
4563**
drh6b9d6dd2008-12-03 19:34:47 +00004564**
drh7708e972008-11-29 00:56:52 +00004565** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004566**
drh7708e972008-11-29 00:56:52 +00004567** * A constant sqlite3_io_methods object call METHOD that has locking
4568** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4569**
4570** * An I/O method finder function called FINDER that returns a pointer
4571** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004572*/
drhd9e5c4f2010-05-12 18:01:39 +00004573#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004574static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004575 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004576 CLOSE, /* xClose */ \
4577 unixRead, /* xRead */ \
4578 unixWrite, /* xWrite */ \
4579 unixTruncate, /* xTruncate */ \
4580 unixSync, /* xSync */ \
4581 unixFileSize, /* xFileSize */ \
4582 LOCK, /* xLock */ \
4583 UNLOCK, /* xUnlock */ \
4584 CKLOCK, /* xCheckReservedLock */ \
4585 unixFileControl, /* xFileControl */ \
4586 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004587 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004588 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004589 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004590 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004591 unixShmUnmap, /* xShmUnmap */ \
4592 unixMremap, /* xMremap */ \
drh7708e972008-11-29 00:56:52 +00004593}; \
drh0c2694b2009-09-03 16:23:44 +00004594static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4595 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004596 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004597} \
drh0c2694b2009-09-03 16:23:44 +00004598static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004599 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004600
4601/*
4602** Here are all of the sqlite3_io_methods objects for each of the
4603** locking strategies. Functions that return pointers to these methods
4604** are also created.
4605*/
4606IOMETHODS(
4607 posixIoFinder, /* Finder function name */
4608 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004609 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004610 unixClose, /* xClose method */
4611 unixLock, /* xLock method */
4612 unixUnlock, /* xUnlock method */
4613 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004614)
drh7708e972008-11-29 00:56:52 +00004615IOMETHODS(
4616 nolockIoFinder, /* Finder function name */
4617 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004618 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004619 nolockClose, /* xClose method */
4620 nolockLock, /* xLock method */
4621 nolockUnlock, /* xUnlock method */
4622 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004623)
drh7708e972008-11-29 00:56:52 +00004624IOMETHODS(
4625 dotlockIoFinder, /* Finder function name */
4626 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004627 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004628 dotlockClose, /* xClose method */
4629 dotlockLock, /* xLock method */
4630 dotlockUnlock, /* xUnlock method */
4631 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004632)
drh7708e972008-11-29 00:56:52 +00004633
chw78a13182009-04-07 05:35:03 +00004634#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004635IOMETHODS(
4636 flockIoFinder, /* Finder function name */
4637 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004638 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004639 flockClose, /* xClose method */
4640 flockLock, /* xLock method */
4641 flockUnlock, /* xUnlock method */
4642 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004643)
drh7708e972008-11-29 00:56:52 +00004644#endif
4645
drh6c7d5c52008-11-21 20:32:33 +00004646#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004647IOMETHODS(
4648 semIoFinder, /* Finder function name */
4649 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004650 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004651 semClose, /* xClose method */
4652 semLock, /* xLock method */
4653 semUnlock, /* xUnlock method */
4654 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004655)
aswiftaebf4132008-11-21 00:10:35 +00004656#endif
drh7708e972008-11-29 00:56:52 +00004657
drhd2cb50b2009-01-09 21:41:17 +00004658#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004659IOMETHODS(
4660 afpIoFinder, /* Finder function name */
4661 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004662 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004663 afpClose, /* xClose method */
4664 afpLock, /* xLock method */
4665 afpUnlock, /* xUnlock method */
4666 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004667)
drh715ff302008-12-03 22:32:44 +00004668#endif
4669
4670/*
4671** The proxy locking method is a "super-method" in the sense that it
4672** opens secondary file descriptors for the conch and lock files and
4673** it uses proxy, dot-file, AFP, and flock() locking methods on those
4674** secondary files. For this reason, the division that implements
4675** proxy locking is located much further down in the file. But we need
4676** to go ahead and define the sqlite3_io_methods and finder function
4677** for proxy locking here. So we forward declare the I/O methods.
4678*/
drhd2cb50b2009-01-09 21:41:17 +00004679#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004680static int proxyClose(sqlite3_file*);
4681static int proxyLock(sqlite3_file*, int);
4682static int proxyUnlock(sqlite3_file*, int);
4683static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004684IOMETHODS(
4685 proxyIoFinder, /* Finder function name */
4686 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004687 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004688 proxyClose, /* xClose method */
4689 proxyLock, /* xLock method */
4690 proxyUnlock, /* xUnlock method */
4691 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004692)
aswiftaebf4132008-11-21 00:10:35 +00004693#endif
drh7708e972008-11-29 00:56:52 +00004694
drh7ed97b92010-01-20 13:07:21 +00004695/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4696#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4697IOMETHODS(
4698 nfsIoFinder, /* Finder function name */
4699 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004700 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004701 unixClose, /* xClose method */
4702 unixLock, /* xLock method */
4703 nfsUnlock, /* xUnlock method */
4704 unixCheckReservedLock /* xCheckReservedLock method */
4705)
4706#endif
drh7708e972008-11-29 00:56:52 +00004707
drhd2cb50b2009-01-09 21:41:17 +00004708#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004709/*
drh6b9d6dd2008-12-03 19:34:47 +00004710** This "finder" function attempts to determine the best locking strategy
4711** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004712** object that implements that strategy.
4713**
4714** This is for MacOSX only.
4715*/
drh1875f7a2008-12-08 18:19:17 +00004716static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004717 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004718 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004719){
4720 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004721 const char *zFilesystem; /* Filesystem type name */
4722 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004723 } aMap[] = {
4724 { "hfs", &posixIoMethods },
4725 { "ufs", &posixIoMethods },
4726 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004727 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004728 { "webdav", &nolockIoMethods },
4729 { 0, 0 }
4730 };
4731 int i;
4732 struct statfs fsInfo;
4733 struct flock lockInfo;
4734
4735 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004736 /* If filePath==NULL that means we are dealing with a transient file
4737 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004738 return &nolockIoMethods;
4739 }
4740 if( statfs(filePath, &fsInfo) != -1 ){
4741 if( fsInfo.f_flags & MNT_RDONLY ){
4742 return &nolockIoMethods;
4743 }
4744 for(i=0; aMap[i].zFilesystem; i++){
4745 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4746 return aMap[i].pMethods;
4747 }
4748 }
4749 }
4750
4751 /* Default case. Handles, amongst others, "nfs".
4752 ** Test byte-range lock using fcntl(). If the call succeeds,
4753 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004754 */
drh7708e972008-11-29 00:56:52 +00004755 lockInfo.l_len = 1;
4756 lockInfo.l_start = 0;
4757 lockInfo.l_whence = SEEK_SET;
4758 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004759 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004760 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4761 return &nfsIoMethods;
4762 } else {
4763 return &posixIoMethods;
4764 }
drh7708e972008-11-29 00:56:52 +00004765 }else{
4766 return &dotlockIoMethods;
4767 }
4768}
drh0c2694b2009-09-03 16:23:44 +00004769static const sqlite3_io_methods
4770 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004771
drhd2cb50b2009-01-09 21:41:17 +00004772#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004773
chw78a13182009-04-07 05:35:03 +00004774#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4775/*
4776** This "finder" function attempts to determine the best locking strategy
4777** for the database file "filePath". It then returns the sqlite3_io_methods
4778** object that implements that strategy.
4779**
4780** This is for VXWorks only.
4781*/
4782static const sqlite3_io_methods *autolockIoFinderImpl(
4783 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004784 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004785){
4786 struct flock lockInfo;
4787
4788 if( !filePath ){
4789 /* If filePath==NULL that means we are dealing with a transient file
4790 ** that does not need to be locked. */
4791 return &nolockIoMethods;
4792 }
4793
4794 /* Test if fcntl() is supported and use POSIX style locks.
4795 ** Otherwise fall back to the named semaphore method.
4796 */
4797 lockInfo.l_len = 1;
4798 lockInfo.l_start = 0;
4799 lockInfo.l_whence = SEEK_SET;
4800 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004801 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004802 return &posixIoMethods;
4803 }else{
4804 return &semIoMethods;
4805 }
4806}
drh0c2694b2009-09-03 16:23:44 +00004807static const sqlite3_io_methods
4808 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004809
4810#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4811
drh7708e972008-11-29 00:56:52 +00004812/*
4813** An abstract type for a pointer to a IO method finder function:
4814*/
drh0c2694b2009-09-03 16:23:44 +00004815typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004816
aswiftaebf4132008-11-21 00:10:35 +00004817
drh734c9862008-11-28 15:37:20 +00004818/****************************************************************************
4819**************************** sqlite3_vfs methods ****************************
4820**
4821** This division contains the implementation of methods on the
4822** sqlite3_vfs object.
4823*/
4824
danielk1977a3d4c882007-03-23 10:08:38 +00004825/*
danielk1977e339d652008-06-28 11:23:00 +00004826** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004827*/
4828static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004829 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004830 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004831 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004832 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004833 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004834){
drh7708e972008-11-29 00:56:52 +00004835 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004836 unixFile *pNew = (unixFile *)pId;
4837 int rc = SQLITE_OK;
4838
drh8af6c222010-05-14 12:43:01 +00004839 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004840
dan00157392010-10-05 11:33:15 +00004841 /* Usually the path zFilename should not be a relative pathname. The
4842 ** exception is when opening the proxy "conch" file in builds that
4843 ** include the special Apple locking styles.
4844 */
dan00157392010-10-05 11:33:15 +00004845#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004846 assert( zFilename==0 || zFilename[0]=='/'
4847 || pVfs->pAppData==(void*)&autolockIoFinder );
4848#else
4849 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004850#endif
dan00157392010-10-05 11:33:15 +00004851
drhb07028f2011-10-14 21:49:18 +00004852 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004853 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004854
drh308c2a52010-05-14 11:30:18 +00004855 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004856 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004857 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004858 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004859 pNew->ctrlFlags = (u8)ctrlFlags;
dan6101d502013-03-22 08:58:38 +00004860 VVA_ONLY( pNew->mmapSize = 0; )
drhc02a43a2012-01-10 23:18:38 +00004861 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4862 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004863 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004864 }
drh503a6862013-03-01 01:07:17 +00004865 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00004866 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004867 }
drh339eb0b2008-03-07 15:34:11 +00004868
drh6c7d5c52008-11-21 20:32:33 +00004869#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004870 pNew->pId = vxworksFindFileId(zFilename);
4871 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004872 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004873 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004874 }
4875#endif
4876
drhc02a43a2012-01-10 23:18:38 +00004877 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004878 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004879 }else{
drh0c2694b2009-09-03 16:23:44 +00004880 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004881#if SQLITE_ENABLE_LOCKING_STYLE
4882 /* Cache zFilename in the locking context (AFP and dotlock override) for
4883 ** proxyLock activation is possible (remote proxy is based on db name)
4884 ** zFilename remains valid until file is closed, to support */
4885 pNew->lockingContext = (void*)zFilename;
4886#endif
drhda0e7682008-07-30 15:27:54 +00004887 }
danielk1977e339d652008-06-28 11:23:00 +00004888
drh7ed97b92010-01-20 13:07:21 +00004889 if( pLockingStyle == &posixIoMethods
4890#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4891 || pLockingStyle == &nfsIoMethods
4892#endif
4893 ){
drh7708e972008-11-29 00:56:52 +00004894 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004895 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004896 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004897 /* If an error occured in findInodeInfo(), close the file descriptor
4898 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004899 ** in two scenarios:
4900 **
4901 ** (a) A call to fstat() failed.
4902 ** (b) A malloc failed.
4903 **
4904 ** Scenario (b) may only occur if the process is holding no other
4905 ** file descriptors open on the same file. If there were other file
4906 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004907 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004908 ** handle h - as it is guaranteed that no posix locks will be released
4909 ** by doing so.
4910 **
4911 ** If scenario (a) caused the error then things are not so safe. The
4912 ** implicit assumption here is that if fstat() fails, things are in
4913 ** such bad shape that dropping a lock or two doesn't matter much.
4914 */
drh0e9365c2011-03-02 02:08:13 +00004915 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004916 h = -1;
4917 }
drh7708e972008-11-29 00:56:52 +00004918 unixLeaveMutex();
4919 }
danielk1977e339d652008-06-28 11:23:00 +00004920
drhd2cb50b2009-01-09 21:41:17 +00004921#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004922 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004923 /* AFP locking uses the file path so it needs to be included in
4924 ** the afpLockingContext.
4925 */
4926 afpLockingContext *pCtx;
4927 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4928 if( pCtx==0 ){
4929 rc = SQLITE_NOMEM;
4930 }else{
4931 /* NB: zFilename exists and remains valid until the file is closed
4932 ** according to requirement F11141. So we do not need to make a
4933 ** copy of the filename. */
4934 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004935 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004936 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004937 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004938 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004939 if( rc!=SQLITE_OK ){
4940 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004941 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004942 h = -1;
4943 }
drh7708e972008-11-29 00:56:52 +00004944 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004945 }
drh7708e972008-11-29 00:56:52 +00004946 }
4947#endif
danielk1977e339d652008-06-28 11:23:00 +00004948
drh7708e972008-11-29 00:56:52 +00004949 else if( pLockingStyle == &dotlockIoMethods ){
4950 /* Dotfile locking uses the file path so it needs to be included in
4951 ** the dotlockLockingContext
4952 */
4953 char *zLockFile;
4954 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004955 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004956 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004957 zLockFile = (char *)sqlite3_malloc(nFilename);
4958 if( zLockFile==0 ){
4959 rc = SQLITE_NOMEM;
4960 }else{
4961 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004962 }
drh7708e972008-11-29 00:56:52 +00004963 pNew->lockingContext = zLockFile;
4964 }
danielk1977e339d652008-06-28 11:23:00 +00004965
drh6c7d5c52008-11-21 20:32:33 +00004966#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004967 else if( pLockingStyle == &semIoMethods ){
4968 /* Named semaphore locking uses the file path so it needs to be
4969 ** included in the semLockingContext
4970 */
4971 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004972 rc = findInodeInfo(pNew, &pNew->pInode);
4973 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4974 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004975 int n;
drh2238dcc2009-08-27 17:56:20 +00004976 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004977 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004978 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004979 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004980 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4981 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004982 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004983 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004984 }
chw97185482008-11-17 08:05:31 +00004985 }
drh7708e972008-11-29 00:56:52 +00004986 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004987 }
drh7708e972008-11-29 00:56:52 +00004988#endif
aswift5b1a2562008-08-22 00:22:35 +00004989
4990 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004991#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004992 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004993 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004994 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004995 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004996 isDelete = 0;
4997 }
drhc02a43a2012-01-10 23:18:38 +00004998 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004999#endif
danielk1977e339d652008-06-28 11:23:00 +00005000 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005001 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005002 }else{
drh7708e972008-11-29 00:56:52 +00005003 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005004 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00005005 }
danielk1977e339d652008-06-28 11:23:00 +00005006 return rc;
drh054889e2005-11-30 03:20:31 +00005007}
drh9c06c952005-11-26 00:25:00 +00005008
danielk1977ad94b582007-08-20 06:44:22 +00005009/*
drh8b3cf822010-06-01 21:02:51 +00005010** Return the name of a directory in which to put temporary files.
5011** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005012*/
drh7234c6d2010-06-19 15:10:09 +00005013static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005014 static const char *azDirs[] = {
5015 0,
aswiftaebf4132008-11-21 00:10:35 +00005016 0,
danielk197717b90b52008-06-06 11:11:25 +00005017 "/var/tmp",
5018 "/usr/tmp",
5019 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005020 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005021 };
drh8b3cf822010-06-01 21:02:51 +00005022 unsigned int i;
5023 struct stat buf;
5024 const char *zDir = 0;
5025
5026 azDirs[0] = sqlite3_temp_directory;
5027 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005028 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005029 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005030 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005031 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005032 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005033 break;
5034 }
5035 return zDir;
5036}
5037
5038/*
5039** Create a temporary file name in zBuf. zBuf must be allocated
5040** by the calling process and must be big enough to hold at least
5041** pVfs->mxPathname bytes.
5042*/
5043static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005044 static const unsigned char zChars[] =
5045 "abcdefghijklmnopqrstuvwxyz"
5046 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5047 "0123456789";
drh41022642008-11-21 00:24:42 +00005048 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005049 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005050
5051 /* It's odd to simulate an io-error here, but really this is just
5052 ** using the io-error infrastructure to test that SQLite handles this
5053 ** function failing.
5054 */
5055 SimulateIOError( return SQLITE_IOERR );
5056
drh7234c6d2010-06-19 15:10:09 +00005057 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005058 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005059
5060 /* Check that the output buffer is large enough for the temporary file
5061 ** name. If it is not, return SQLITE_ERROR.
5062 */
drhc02a43a2012-01-10 23:18:38 +00005063 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005064 return SQLITE_ERROR;
5065 }
5066
5067 do{
drhc02a43a2012-01-10 23:18:38 +00005068 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005069 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005070 sqlite3_randomness(15, &zBuf[j]);
5071 for(i=0; i<15; i++, j++){
5072 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5073 }
5074 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005075 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005076 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005077 return SQLITE_OK;
5078}
5079
drhd2cb50b2009-01-09 21:41:17 +00005080#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005081/*
5082** Routine to transform a unixFile into a proxy-locking unixFile.
5083** Implementation in the proxy-lock division, but used by unixOpen()
5084** if SQLITE_PREFER_PROXY_LOCKING is defined.
5085*/
5086static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005087#endif
drhc66d5b62008-12-03 22:48:32 +00005088
dan08da86a2009-08-21 17:18:03 +00005089/*
5090** Search for an unused file descriptor that was opened on the database
5091** file (not a journal or master-journal file) identified by pathname
5092** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5093** argument to this function.
5094**
5095** Such a file descriptor may exist if a database connection was closed
5096** but the associated file descriptor could not be closed because some
5097** other file descriptor open on the same file is holding a file-lock.
5098** Refer to comments in the unixClose() function and the lengthy comment
5099** describing "Posix Advisory Locking" at the start of this file for
5100** further details. Also, ticket #4018.
5101**
5102** If a suitable file descriptor is found, then it is returned. If no
5103** such file descriptor is located, -1 is returned.
5104*/
dane946c392009-08-22 11:39:46 +00005105static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5106 UnixUnusedFd *pUnused = 0;
5107
5108 /* Do not search for an unused file descriptor on vxworks. Not because
5109 ** vxworks would not benefit from the change (it might, we're not sure),
5110 ** but because no way to test it is currently available. It is better
5111 ** not to risk breaking vxworks support for the sake of such an obscure
5112 ** feature. */
5113#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005114 struct stat sStat; /* Results of stat() call */
5115
5116 /* A stat() call may fail for various reasons. If this happens, it is
5117 ** almost certain that an open() call on the same path will also fail.
5118 ** For this reason, if an error occurs in the stat() call here, it is
5119 ** ignored and -1 is returned. The caller will try to open a new file
5120 ** descriptor on the same path, fail, and return an error to SQLite.
5121 **
5122 ** Even if a subsequent open() call does succeed, the consequences of
5123 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005124 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005125 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005126
5127 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005128 pInode = inodeList;
5129 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5130 || pInode->fileId.ino!=sStat.st_ino) ){
5131 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005132 }
drh8af6c222010-05-14 12:43:01 +00005133 if( pInode ){
dane946c392009-08-22 11:39:46 +00005134 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005135 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005136 pUnused = *pp;
5137 if( pUnused ){
5138 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005139 }
5140 }
5141 unixLeaveMutex();
5142 }
dane946c392009-08-22 11:39:46 +00005143#endif /* if !OS_VXWORKS */
5144 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005145}
danielk197717b90b52008-06-06 11:11:25 +00005146
5147/*
danddb0ac42010-07-14 14:48:58 +00005148** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005149** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005150** and a value suitable for passing as the third argument to open(2) is
5151** written to *pMode. If an IO error occurs, an SQLite error code is
5152** returned and the value of *pMode is not modified.
5153**
drh8c815d12012-02-13 20:16:37 +00005154** In most cases cases, this routine sets *pMode to 0, which will become
5155** an indication to robust_open() to create the file using
5156** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5157** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005158** this function queries the file-system for the permissions on the
5159** corresponding database file and sets *pMode to this value. Whenever
5160** possible, WAL and journal files are created using the same permissions
5161** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005162**
5163** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5164** original filename is unavailable. But 8_3_NAMES is only used for
5165** FAT filesystems and permissions do not matter there, so just use
5166** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005167*/
5168static int findCreateFileMode(
5169 const char *zPath, /* Path of file (possibly) being created */
5170 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005171 mode_t *pMode, /* OUT: Permissions to open file with */
5172 uid_t *pUid, /* OUT: uid to set on the file */
5173 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005174){
5175 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005176 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005177 *pUid = 0;
5178 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005179 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005180 char zDb[MAX_PATHNAME+1]; /* Database file path */
5181 int nDb; /* Number of valid bytes in zDb */
5182 struct stat sStat; /* Output of stat() on database file */
5183
dana0c989d2010-11-05 18:07:37 +00005184 /* zPath is a path to a WAL or journal file. The following block derives
5185 ** the path to the associated database file from zPath. This block handles
5186 ** the following naming conventions:
5187 **
5188 ** "<path to db>-journal"
5189 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005190 ** "<path to db>-journalNN"
5191 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005192 **
drhd337c5b2011-10-20 18:23:35 +00005193 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005194 ** used by the test_multiplex.c module.
5195 */
5196 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005197#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005198 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005199 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005200#else
5201 while( zPath[nDb]!='-' ){
5202 assert( nDb>0 );
5203 assert( zPath[nDb]!='\n' );
5204 nDb--;
5205 }
5206#endif
danddb0ac42010-07-14 14:48:58 +00005207 memcpy(zDb, zPath, nDb);
5208 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005209
drh58384f12011-07-28 00:14:45 +00005210 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005211 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005212 *pUid = sStat.st_uid;
5213 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005214 }else{
5215 rc = SQLITE_IOERR_FSTAT;
5216 }
5217 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5218 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005219 }
5220 return rc;
5221}
5222
5223/*
danielk1977ad94b582007-08-20 06:44:22 +00005224** Open the file zPath.
5225**
danielk1977b4b47412007-08-17 15:53:36 +00005226** Previously, the SQLite OS layer used three functions in place of this
5227** one:
5228**
5229** sqlite3OsOpenReadWrite();
5230** sqlite3OsOpenReadOnly();
5231** sqlite3OsOpenExclusive();
5232**
5233** These calls correspond to the following combinations of flags:
5234**
5235** ReadWrite() -> (READWRITE | CREATE)
5236** ReadOnly() -> (READONLY)
5237** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5238**
5239** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5240** true, the file was configured to be automatically deleted when the
5241** file handle closed. To achieve the same effect using this new
5242** interface, add the DELETEONCLOSE flag to those specified above for
5243** OpenExclusive().
5244*/
5245static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005246 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5247 const char *zPath, /* Pathname of file to be opened */
5248 sqlite3_file *pFile, /* The file descriptor to be filled in */
5249 int flags, /* Input flags to control the opening */
5250 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005251){
dan08da86a2009-08-21 17:18:03 +00005252 unixFile *p = (unixFile *)pFile;
5253 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005254 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005255 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005256 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005257 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005258 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005259
5260 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5261 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5262 int isCreate = (flags & SQLITE_OPEN_CREATE);
5263 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5264 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005265#if SQLITE_ENABLE_LOCKING_STYLE
5266 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5267#endif
drh3d4435b2011-08-26 20:55:50 +00005268#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5269 struct statfs fsInfo;
5270#endif
danielk1977b4b47412007-08-17 15:53:36 +00005271
danielk1977fee2d252007-08-18 10:59:19 +00005272 /* If creating a master or main-file journal, this function will open
5273 ** a file-descriptor on the directory too. The first time unixSync()
5274 ** is called the directory file descriptor will be fsync()ed and close()d.
5275 */
drh0059eae2011-08-08 23:48:40 +00005276 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005277 eType==SQLITE_OPEN_MASTER_JOURNAL
5278 || eType==SQLITE_OPEN_MAIN_JOURNAL
5279 || eType==SQLITE_OPEN_WAL
5280 ));
danielk1977fee2d252007-08-18 10:59:19 +00005281
danielk197717b90b52008-06-06 11:11:25 +00005282 /* If argument zPath is a NULL pointer, this function is required to open
5283 ** a temporary file. Use this buffer to store the file name in.
5284 */
drhc02a43a2012-01-10 23:18:38 +00005285 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005286 const char *zName = zPath;
5287
danielk1977fee2d252007-08-18 10:59:19 +00005288 /* Check the following statements are true:
5289 **
5290 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5291 ** (b) if CREATE is set, then READWRITE must also be set, and
5292 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005293 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005294 */
danielk1977b4b47412007-08-17 15:53:36 +00005295 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005296 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005297 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005298 assert(isDelete==0 || isCreate);
5299
danddb0ac42010-07-14 14:48:58 +00005300 /* The main DB, main journal, WAL file and master journal are never
5301 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005302 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5303 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5304 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005305 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005306
danielk1977fee2d252007-08-18 10:59:19 +00005307 /* Assert that the upper layer has set one of the "file-type" flags. */
5308 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5309 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5310 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005311 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005312 );
5313
dan08da86a2009-08-21 17:18:03 +00005314 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005315
dan08da86a2009-08-21 17:18:03 +00005316 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005317 UnixUnusedFd *pUnused;
5318 pUnused = findReusableFd(zName, flags);
5319 if( pUnused ){
5320 fd = pUnused->fd;
5321 }else{
dan6aa657f2009-08-24 18:57:58 +00005322 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005323 if( !pUnused ){
5324 return SQLITE_NOMEM;
5325 }
5326 }
5327 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005328
5329 /* Database filenames are double-zero terminated if they are not
5330 ** URIs with parameters. Hence, they can always be passed into
5331 ** sqlite3_uri_parameter(). */
5332 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5333
dan08da86a2009-08-21 17:18:03 +00005334 }else if( !zName ){
5335 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005336 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005337 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005338 if( rc!=SQLITE_OK ){
5339 return rc;
5340 }
5341 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005342
5343 /* Generated temporary filenames are always double-zero terminated
5344 ** for use by sqlite3_uri_parameter(). */
5345 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005346 }
5347
dan08da86a2009-08-21 17:18:03 +00005348 /* Determine the value of the flags parameter passed to POSIX function
5349 ** open(). These must be calculated even if open() is not called, as
5350 ** they may be stored as part of the file handle and used by the
5351 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005352 if( isReadonly ) openFlags |= O_RDONLY;
5353 if( isReadWrite ) openFlags |= O_RDWR;
5354 if( isCreate ) openFlags |= O_CREAT;
5355 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5356 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005357
danielk1977b4b47412007-08-17 15:53:36 +00005358 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005359 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005360 uid_t uid; /* Userid for the file */
5361 gid_t gid; /* Groupid for the file */
5362 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005363 if( rc!=SQLITE_OK ){
5364 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005365 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005366 return rc;
5367 }
drhad4f1e52011-03-04 15:43:57 +00005368 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005369 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005370 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5371 /* Failed to open the file for read/write access. Try read-only. */
5372 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005373 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005374 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005375 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005376 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005377 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005378 }
5379 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005380 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005381 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005382 }
drhac7c3ac2012-02-11 19:23:48 +00005383
5384 /* If this process is running as root and if creating a new rollback
5385 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005386 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005387 */
5388 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005389 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005390 }
danielk1977b4b47412007-08-17 15:53:36 +00005391 }
dan08da86a2009-08-21 17:18:03 +00005392 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005393 if( pOutFlags ){
5394 *pOutFlags = flags;
5395 }
5396
dane946c392009-08-22 11:39:46 +00005397 if( p->pUnused ){
5398 p->pUnused->fd = fd;
5399 p->pUnused->flags = flags;
5400 }
5401
danielk1977b4b47412007-08-17 15:53:36 +00005402 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005403#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005404 zPath = zName;
5405#else
drh036ac7f2011-08-08 23:18:05 +00005406 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005407#endif
danielk1977b4b47412007-08-17 15:53:36 +00005408 }
drh41022642008-11-21 00:24:42 +00005409#if SQLITE_ENABLE_LOCKING_STYLE
5410 else{
dan08da86a2009-08-21 17:18:03 +00005411 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005412 }
5413#endif
5414
drhda0e7682008-07-30 15:27:54 +00005415 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005416
drh7ed97b92010-01-20 13:07:21 +00005417
5418#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005419 if( fstatfs(fd, &fsInfo) == -1 ){
5420 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005421 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005422 return SQLITE_IOERR_ACCESS;
5423 }
5424 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5425 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5426 }
5427#endif
drhc02a43a2012-01-10 23:18:38 +00005428
5429 /* Set up appropriate ctrlFlags */
5430 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5431 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5432 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5433 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5434 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5435
drh7ed97b92010-01-20 13:07:21 +00005436#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005437#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005438 isAutoProxy = 1;
5439#endif
5440 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005441 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5442 int useProxy = 0;
5443
dan08da86a2009-08-21 17:18:03 +00005444 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5445 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005446 if( envforce!=NULL ){
5447 useProxy = atoi(envforce)>0;
5448 }else{
aswiftaebf4132008-11-21 00:10:35 +00005449 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005450 /* In theory, the close(fd) call is sub-optimal. If the file opened
5451 ** with fd is a database file, and there are other connections open
5452 ** on that file that are currently holding advisory locks on it,
5453 ** then the call to close() will cancel those locks. In practice,
5454 ** we're assuming that statfs() doesn't fail very often. At least
5455 ** not while other file descriptors opened by the same process on
5456 ** the same file are working. */
5457 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005458 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005459 rc = SQLITE_IOERR_ACCESS;
5460 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005461 }
5462 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5463 }
5464 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005465 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005466 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005467 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005468 if( rc!=SQLITE_OK ){
5469 /* Use unixClose to clean up the resources added in fillInUnixFile
5470 ** and clear all the structure's references. Specifically,
5471 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5472 */
5473 unixClose(pFile);
5474 return rc;
5475 }
aswiftaebf4132008-11-21 00:10:35 +00005476 }
dane946c392009-08-22 11:39:46 +00005477 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005478 }
5479 }
5480#endif
5481
drhc02a43a2012-01-10 23:18:38 +00005482 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5483
dane946c392009-08-22 11:39:46 +00005484open_finished:
5485 if( rc!=SQLITE_OK ){
5486 sqlite3_free(p->pUnused);
5487 }
5488 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005489}
5490
dane946c392009-08-22 11:39:46 +00005491
danielk1977b4b47412007-08-17 15:53:36 +00005492/*
danielk1977fee2d252007-08-18 10:59:19 +00005493** Delete the file at zPath. If the dirSync argument is true, fsync()
5494** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005495*/
drh6b9d6dd2008-12-03 19:34:47 +00005496static int unixDelete(
5497 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5498 const char *zPath, /* Name of file to be deleted */
5499 int dirSync /* If true, fsync() directory after deleting file */
5500){
danielk1977fee2d252007-08-18 10:59:19 +00005501 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005502 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005503 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005504 if( osUnlink(zPath)==(-1) ){
5505 if( errno==ENOENT ){
5506 rc = SQLITE_IOERR_DELETE_NOENT;
5507 }else{
drhb4308162012-11-09 21:40:02 +00005508 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005509 }
drhb4308162012-11-09 21:40:02 +00005510 return rc;
drh5d4feff2010-07-14 01:45:22 +00005511 }
danielk1977d39fa702008-10-16 13:27:40 +00005512#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005513 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005514 int fd;
drh90315a22011-08-10 01:52:12 +00005515 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005516 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005517#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005518 if( fsync(fd)==-1 )
5519#else
5520 if( fsync(fd) )
5521#endif
5522 {
dane18d4952011-02-21 11:46:24 +00005523 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005524 }
drh0e9365c2011-03-02 02:08:13 +00005525 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005526 }else if( rc==SQLITE_CANTOPEN ){
5527 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005528 }
5529 }
danielk1977d138dd82008-10-15 16:02:48 +00005530#endif
danielk1977fee2d252007-08-18 10:59:19 +00005531 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005532}
5533
danielk197790949c22007-08-17 16:50:38 +00005534/*
5535** Test the existance of or access permissions of file zPath. The
5536** test performed depends on the value of flags:
5537**
5538** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5539** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5540** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5541**
5542** Otherwise return 0.
5543*/
danielk1977861f7452008-06-05 11:39:11 +00005544static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005545 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5546 const char *zPath, /* Path of the file to examine */
5547 int flags, /* What do we want to learn about the zPath file? */
5548 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005549){
rse25c0d1a2007-09-20 08:38:14 +00005550 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005551 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005552 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005553 switch( flags ){
5554 case SQLITE_ACCESS_EXISTS:
5555 amode = F_OK;
5556 break;
5557 case SQLITE_ACCESS_READWRITE:
5558 amode = W_OK|R_OK;
5559 break;
drh50d3f902007-08-27 21:10:36 +00005560 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005561 amode = R_OK;
5562 break;
5563
5564 default:
5565 assert(!"Invalid flags argument");
5566 }
drh99ab3b12011-03-02 15:09:07 +00005567 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005568 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5569 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005570 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005571 *pResOut = 0;
5572 }
5573 }
danielk1977861f7452008-06-05 11:39:11 +00005574 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005575}
5576
danielk1977b4b47412007-08-17 15:53:36 +00005577
5578/*
5579** Turn a relative pathname into a full pathname. The relative path
5580** is stored as a nul-terminated string in the buffer pointed to by
5581** zPath.
5582**
5583** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5584** (in this case, MAX_PATHNAME bytes). The full-path is written to
5585** this buffer before returning.
5586*/
danielk1977adfb9b02007-09-17 07:02:56 +00005587static int unixFullPathname(
5588 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5589 const char *zPath, /* Possibly relative input path */
5590 int nOut, /* Size of output buffer in bytes */
5591 char *zOut /* Output buffer */
5592){
danielk1977843e65f2007-09-01 16:16:15 +00005593
5594 /* It's odd to simulate an io-error here, but really this is just
5595 ** using the io-error infrastructure to test that SQLite handles this
5596 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005597 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005598 */
5599 SimulateIOError( return SQLITE_ERROR );
5600
drh153c62c2007-08-24 03:51:33 +00005601 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005602 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005603
drh3c7f2dc2007-12-06 13:26:20 +00005604 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005605 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005606 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005607 }else{
5608 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005609 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005610 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005611 }
drhea678832008-12-10 19:26:22 +00005612 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005613 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005614 }
5615 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005616}
5617
drh0ccebe72005-06-07 22:22:50 +00005618
drh761df872006-12-21 01:29:22 +00005619#ifndef SQLITE_OMIT_LOAD_EXTENSION
5620/*
5621** Interfaces for opening a shared library, finding entry points
5622** within the shared library, and closing the shared library.
5623*/
5624#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005625static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5626 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005627 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5628}
danielk197795c8a542007-09-01 06:51:27 +00005629
5630/*
5631** SQLite calls this function immediately after a call to unixDlSym() or
5632** unixDlOpen() fails (returns a null pointer). If a more detailed error
5633** message is available, it is written to zBufOut. If no error message
5634** is available, zBufOut is left unmodified and SQLite uses a default
5635** error message.
5636*/
danielk1977397d65f2008-11-19 11:35:39 +00005637static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005638 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005639 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005640 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005641 zErr = dlerror();
5642 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005643 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005644 }
drh6c7d5c52008-11-21 20:32:33 +00005645 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005646}
drh1875f7a2008-12-08 18:19:17 +00005647static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5648 /*
5649 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5650 ** cast into a pointer to a function. And yet the library dlsym() routine
5651 ** returns a void* which is really a pointer to a function. So how do we
5652 ** use dlsym() with -pedantic-errors?
5653 **
5654 ** Variable x below is defined to be a pointer to a function taking
5655 ** parameters void* and const char* and returning a pointer to a function.
5656 ** We initialize x by assigning it a pointer to the dlsym() function.
5657 ** (That assignment requires a cast.) Then we call the function that
5658 ** x points to.
5659 **
5660 ** This work-around is unlikely to work correctly on any system where
5661 ** you really cannot cast a function pointer into void*. But then, on the
5662 ** other hand, dlsym() will not work on such a system either, so we have
5663 ** not really lost anything.
5664 */
5665 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005666 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005667 x = (void(*(*)(void*,const char*))(void))dlsym;
5668 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005669}
danielk1977397d65f2008-11-19 11:35:39 +00005670static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5671 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005672 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005673}
danielk1977b4b47412007-08-17 15:53:36 +00005674#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5675 #define unixDlOpen 0
5676 #define unixDlError 0
5677 #define unixDlSym 0
5678 #define unixDlClose 0
5679#endif
5680
5681/*
danielk197790949c22007-08-17 16:50:38 +00005682** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005683*/
danielk1977397d65f2008-11-19 11:35:39 +00005684static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5685 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005686 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005687
drhbbd42a62004-05-22 17:41:58 +00005688 /* We have to initialize zBuf to prevent valgrind from reporting
5689 ** errors. The reports issued by valgrind are incorrect - we would
5690 ** prefer that the randomness be increased by making use of the
5691 ** uninitialized space in zBuf - but valgrind errors tend to worry
5692 ** some users. Rather than argue, it seems easier just to initialize
5693 ** the whole array and silence valgrind, even if that means less randomness
5694 ** in the random seed.
5695 **
5696 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005697 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005698 ** tests repeatable.
5699 */
danielk1977b4b47412007-08-17 15:53:36 +00005700 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005701#if !defined(SQLITE_TEST)
5702 {
drhc18b4042012-02-10 03:10:27 +00005703 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005704 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005705 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005706 time_t t;
5707 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005708 memcpy(zBuf, &t, sizeof(t));
5709 pid = getpid();
5710 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005711 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005712 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005713 }else{
drhc18b4042012-02-10 03:10:27 +00005714 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005715 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005716 }
drhbbd42a62004-05-22 17:41:58 +00005717 }
5718#endif
drh72cbd072008-10-14 17:58:38 +00005719 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005720}
5721
danielk1977b4b47412007-08-17 15:53:36 +00005722
drhbbd42a62004-05-22 17:41:58 +00005723/*
5724** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005725** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005726** The return value is the number of microseconds of sleep actually
5727** requested from the underlying operating system, a number which
5728** might be greater than or equal to the argument, but not less
5729** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005730*/
danielk1977397d65f2008-11-19 11:35:39 +00005731static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005732#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005733 struct timespec sp;
5734
5735 sp.tv_sec = microseconds / 1000000;
5736 sp.tv_nsec = (microseconds % 1000000) * 1000;
5737 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005738 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005739 return microseconds;
5740#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005741 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005742 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005743 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005744#else
danielk1977b4b47412007-08-17 15:53:36 +00005745 int seconds = (microseconds+999999)/1000000;
5746 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005747 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005748 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005749#endif
drh88f474a2006-01-02 20:00:12 +00005750}
5751
5752/*
drh6b9d6dd2008-12-03 19:34:47 +00005753** The following variable, if set to a non-zero value, is interpreted as
5754** the number of seconds since 1970 and is used to set the result of
5755** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005756*/
5757#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005758int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005759#endif
5760
5761/*
drhb7e8ea22010-05-03 14:32:30 +00005762** Find the current time (in Universal Coordinated Time). Write into *piNow
5763** the current time and date as a Julian Day number times 86_400_000. In
5764** other words, write into *piNow the number of milliseconds since the Julian
5765** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5766** proleptic Gregorian calendar.
5767**
drh31702252011-10-12 23:13:43 +00005768** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5769** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005770*/
5771static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5772 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005773 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005774#if defined(NO_GETTOD)
5775 time_t t;
5776 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005777 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005778#elif OS_VXWORKS
5779 struct timespec sNow;
5780 clock_gettime(CLOCK_REALTIME, &sNow);
5781 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5782#else
5783 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005784 if( gettimeofday(&sNow, 0)==0 ){
5785 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5786 }else{
5787 rc = SQLITE_ERROR;
5788 }
drhb7e8ea22010-05-03 14:32:30 +00005789#endif
5790
5791#ifdef SQLITE_TEST
5792 if( sqlite3_current_time ){
5793 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5794 }
5795#endif
5796 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005797 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005798}
5799
5800/*
drhbbd42a62004-05-22 17:41:58 +00005801** Find the current time (in Universal Coordinated Time). Write the
5802** current time and date as a Julian Day number into *prNow and
5803** return 0. Return 1 if the time and date cannot be found.
5804*/
danielk1977397d65f2008-11-19 11:35:39 +00005805static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005806 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005807 int rc;
drhff828942010-06-26 21:34:06 +00005808 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005809 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005810 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005811 return rc;
drhbbd42a62004-05-22 17:41:58 +00005812}
danielk1977b4b47412007-08-17 15:53:36 +00005813
drh6b9d6dd2008-12-03 19:34:47 +00005814/*
5815** We added the xGetLastError() method with the intention of providing
5816** better low-level error messages when operating-system problems come up
5817** during SQLite operation. But so far, none of that has been implemented
5818** in the core. So this routine is never called. For now, it is merely
5819** a place-holder.
5820*/
danielk1977397d65f2008-11-19 11:35:39 +00005821static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5822 UNUSED_PARAMETER(NotUsed);
5823 UNUSED_PARAMETER(NotUsed2);
5824 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005825 return 0;
5826}
5827
drhf2424c52010-04-26 00:04:55 +00005828
5829/*
drh734c9862008-11-28 15:37:20 +00005830************************ End of sqlite3_vfs methods ***************************
5831******************************************************************************/
5832
drh715ff302008-12-03 22:32:44 +00005833/******************************************************************************
5834************************** Begin Proxy Locking ********************************
5835**
5836** Proxy locking is a "uber-locking-method" in this sense: It uses the
5837** other locking methods on secondary lock files. Proxy locking is a
5838** meta-layer over top of the primitive locking implemented above. For
5839** this reason, the division that implements of proxy locking is deferred
5840** until late in the file (here) after all of the other I/O methods have
5841** been defined - so that the primitive locking methods are available
5842** as services to help with the implementation of proxy locking.
5843**
5844****
5845**
5846** The default locking schemes in SQLite use byte-range locks on the
5847** database file to coordinate safe, concurrent access by multiple readers
5848** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5849** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5850** as POSIX read & write locks over fixed set of locations (via fsctl),
5851** on AFP and SMB only exclusive byte-range locks are available via fsctl
5852** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5853** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5854** address in the shared range is taken for a SHARED lock, the entire
5855** shared range is taken for an EXCLUSIVE lock):
5856**
drhf2f105d2012-08-20 15:53:54 +00005857** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00005858** RESERVED_BYTE 0x40000001
5859** SHARED_RANGE 0x40000002 -> 0x40000200
5860**
5861** This works well on the local file system, but shows a nearly 100x
5862** slowdown in read performance on AFP because the AFP client disables
5863** the read cache when byte-range locks are present. Enabling the read
5864** cache exposes a cache coherency problem that is present on all OS X
5865** supported network file systems. NFS and AFP both observe the
5866** close-to-open semantics for ensuring cache coherency
5867** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5868** address the requirements for concurrent database access by multiple
5869** readers and writers
5870** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5871**
5872** To address the performance and cache coherency issues, proxy file locking
5873** changes the way database access is controlled by limiting access to a
5874** single host at a time and moving file locks off of the database file
5875** and onto a proxy file on the local file system.
5876**
5877**
5878** Using proxy locks
5879** -----------------
5880**
5881** C APIs
5882**
5883** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5884** <proxy_path> | ":auto:");
5885** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5886**
5887**
5888** SQL pragmas
5889**
5890** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5891** PRAGMA [database.]lock_proxy_file
5892**
5893** Specifying ":auto:" means that if there is a conch file with a matching
5894** host ID in it, the proxy path in the conch file will be used, otherwise
5895** a proxy path based on the user's temp dir
5896** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5897** actual proxy file name is generated from the name and path of the
5898** database file. For example:
5899**
5900** For database path "/Users/me/foo.db"
5901** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5902**
5903** Once a lock proxy is configured for a database connection, it can not
5904** be removed, however it may be switched to a different proxy path via
5905** the above APIs (assuming the conch file is not being held by another
5906** connection or process).
5907**
5908**
5909** How proxy locking works
5910** -----------------------
5911**
5912** Proxy file locking relies primarily on two new supporting files:
5913**
5914** * conch file to limit access to the database file to a single host
5915** at a time
5916**
5917** * proxy file to act as a proxy for the advisory locks normally
5918** taken on the database
5919**
5920** The conch file - to use a proxy file, sqlite must first "hold the conch"
5921** by taking an sqlite-style shared lock on the conch file, reading the
5922** contents and comparing the host's unique host ID (see below) and lock
5923** proxy path against the values stored in the conch. The conch file is
5924** stored in the same directory as the database file and the file name
5925** is patterned after the database file name as ".<databasename>-conch".
5926** If the conch file does not exist, or it's contents do not match the
5927** host ID and/or proxy path, then the lock is escalated to an exclusive
5928** lock and the conch file contents is updated with the host ID and proxy
5929** path and the lock is downgraded to a shared lock again. If the conch
5930** is held by another process (with a shared lock), the exclusive lock
5931** will fail and SQLITE_BUSY is returned.
5932**
5933** The proxy file - a single-byte file used for all advisory file locks
5934** normally taken on the database file. This allows for safe sharing
5935** of the database file for multiple readers and writers on the same
5936** host (the conch ensures that they all use the same local lock file).
5937**
drh715ff302008-12-03 22:32:44 +00005938** Requesting the lock proxy does not immediately take the conch, it is
5939** only taken when the first request to lock database file is made.
5940** This matches the semantics of the traditional locking behavior, where
5941** opening a connection to a database file does not take a lock on it.
5942** The shared lock and an open file descriptor are maintained until
5943** the connection to the database is closed.
5944**
5945** The proxy file and the lock file are never deleted so they only need
5946** to be created the first time they are used.
5947**
5948** Configuration options
5949** ---------------------
5950**
5951** SQLITE_PREFER_PROXY_LOCKING
5952**
5953** Database files accessed on non-local file systems are
5954** automatically configured for proxy locking, lock files are
5955** named automatically using the same logic as
5956** PRAGMA lock_proxy_file=":auto:"
5957**
5958** SQLITE_PROXY_DEBUG
5959**
5960** Enables the logging of error messages during host id file
5961** retrieval and creation
5962**
drh715ff302008-12-03 22:32:44 +00005963** LOCKPROXYDIR
5964**
5965** Overrides the default directory used for lock proxy files that
5966** are named automatically via the ":auto:" setting
5967**
5968** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5969**
5970** Permissions to use when creating a directory for storing the
5971** lock proxy files, only used when LOCKPROXYDIR is not set.
5972**
5973**
5974** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5975** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5976** force proxy locking to be used for every database file opened, and 0
5977** will force automatic proxy locking to be disabled for all database
5978** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5979** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5980*/
5981
5982/*
5983** Proxy locking is only available on MacOSX
5984*/
drhd2cb50b2009-01-09 21:41:17 +00005985#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005986
drh715ff302008-12-03 22:32:44 +00005987/*
5988** The proxyLockingContext has the path and file structures for the remote
5989** and local proxy files in it
5990*/
5991typedef struct proxyLockingContext proxyLockingContext;
5992struct proxyLockingContext {
5993 unixFile *conchFile; /* Open conch file */
5994 char *conchFilePath; /* Name of the conch file */
5995 unixFile *lockProxy; /* Open proxy lock file */
5996 char *lockProxyPath; /* Name of the proxy lock file */
5997 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005998 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005999 void *oldLockingContext; /* Original lockingcontext to restore on close */
6000 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6001};
6002
drh7ed97b92010-01-20 13:07:21 +00006003/*
6004** The proxy lock file path for the database at dbPath is written into lPath,
6005** which must point to valid, writable memory large enough for a maxLen length
6006** file path.
drh715ff302008-12-03 22:32:44 +00006007*/
drh715ff302008-12-03 22:32:44 +00006008static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6009 int len;
6010 int dbLen;
6011 int i;
6012
6013#ifdef LOCKPROXYDIR
6014 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6015#else
6016# ifdef _CS_DARWIN_USER_TEMP_DIR
6017 {
drh7ed97b92010-01-20 13:07:21 +00006018 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006019 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6020 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006021 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006022 }
drh7ed97b92010-01-20 13:07:21 +00006023 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006024 }
6025# else
6026 len = strlcpy(lPath, "/tmp/", maxLen);
6027# endif
6028#endif
6029
6030 if( lPath[len-1]!='/' ){
6031 len = strlcat(lPath, "/", maxLen);
6032 }
6033
6034 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006035 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006036 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006037 char c = dbPath[i];
6038 lPath[i+len] = (c=='/')?'_':c;
6039 }
6040 lPath[i+len]='\0';
6041 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006042 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006043 return SQLITE_OK;
6044}
6045
drh7ed97b92010-01-20 13:07:21 +00006046/*
6047 ** Creates the lock file and any missing directories in lockPath
6048 */
6049static int proxyCreateLockPath(const char *lockPath){
6050 int i, len;
6051 char buf[MAXPATHLEN];
6052 int start = 0;
6053
6054 assert(lockPath!=NULL);
6055 /* try to create all the intermediate directories */
6056 len = (int)strlen(lockPath);
6057 buf[0] = lockPath[0];
6058 for( i=1; i<len; i++ ){
6059 if( lockPath[i] == '/' && (i - start > 0) ){
6060 /* only mkdir if leaf dir != "." or "/" or ".." */
6061 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6062 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6063 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006064 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006065 int err=errno;
6066 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006067 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006068 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006069 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006070 return err;
6071 }
6072 }
6073 }
6074 start=i+1;
6075 }
6076 buf[i] = lockPath[i];
6077 }
drh308c2a52010-05-14 11:30:18 +00006078 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006079 return 0;
6080}
6081
drh715ff302008-12-03 22:32:44 +00006082/*
6083** Create a new VFS file descriptor (stored in memory obtained from
6084** sqlite3_malloc) and open the file named "path" in the file descriptor.
6085**
6086** The caller is responsible not only for closing the file descriptor
6087** but also for freeing the memory associated with the file descriptor.
6088*/
drh7ed97b92010-01-20 13:07:21 +00006089static int proxyCreateUnixFile(
6090 const char *path, /* path for the new unixFile */
6091 unixFile **ppFile, /* unixFile created and returned by ref */
6092 int islockfile /* if non zero missing dirs will be created */
6093) {
6094 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006095 unixFile *pNew;
6096 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006097 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006098 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006099 int terrno = 0;
6100 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006101
drh7ed97b92010-01-20 13:07:21 +00006102 /* 1. first try to open/create the file
6103 ** 2. if that fails, and this is a lock file (not-conch), try creating
6104 ** the parent directories and then try again.
6105 ** 3. if that fails, try to open the file read-only
6106 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6107 */
6108 pUnused = findReusableFd(path, openFlags);
6109 if( pUnused ){
6110 fd = pUnused->fd;
6111 }else{
6112 pUnused = sqlite3_malloc(sizeof(*pUnused));
6113 if( !pUnused ){
6114 return SQLITE_NOMEM;
6115 }
6116 }
6117 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006118 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006119 terrno = errno;
6120 if( fd<0 && errno==ENOENT && islockfile ){
6121 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006122 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006123 }
6124 }
6125 }
6126 if( fd<0 ){
6127 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006128 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006129 terrno = errno;
6130 }
6131 if( fd<0 ){
6132 if( islockfile ){
6133 return SQLITE_BUSY;
6134 }
6135 switch (terrno) {
6136 case EACCES:
6137 return SQLITE_PERM;
6138 case EIO:
6139 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6140 default:
drh9978c972010-02-23 17:36:32 +00006141 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006142 }
6143 }
6144
6145 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6146 if( pNew==NULL ){
6147 rc = SQLITE_NOMEM;
6148 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006149 }
6150 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006151 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006152 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006153 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006154 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006155 pUnused->fd = fd;
6156 pUnused->flags = openFlags;
6157 pNew->pUnused = pUnused;
6158
drhc02a43a2012-01-10 23:18:38 +00006159 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006160 if( rc==SQLITE_OK ){
6161 *ppFile = pNew;
6162 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006163 }
drh7ed97b92010-01-20 13:07:21 +00006164end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006165 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006166 sqlite3_free(pNew);
6167 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006168 return rc;
6169}
6170
drh7ed97b92010-01-20 13:07:21 +00006171#ifdef SQLITE_TEST
6172/* simulate multiple hosts by creating unique hostid file paths */
6173int sqlite3_hostid_num = 0;
6174#endif
6175
6176#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6177
drh0ab216a2010-07-02 17:10:40 +00006178/* Not always defined in the headers as it ought to be */
6179extern int gethostuuid(uuid_t id, const struct timespec *wait);
6180
drh7ed97b92010-01-20 13:07:21 +00006181/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6182** bytes of writable memory.
6183*/
6184static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006185 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6186 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006187#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6188 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006189 {
6190 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6191 if( gethostuuid(pHostID, &timeout) ){
6192 int err = errno;
6193 if( pError ){
6194 *pError = err;
6195 }
6196 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006197 }
drh7ed97b92010-01-20 13:07:21 +00006198 }
drh3d4435b2011-08-26 20:55:50 +00006199#else
6200 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006201#endif
drh7ed97b92010-01-20 13:07:21 +00006202#ifdef SQLITE_TEST
6203 /* simulate multiple hosts by creating unique hostid file paths */
6204 if( sqlite3_hostid_num != 0){
6205 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6206 }
6207#endif
6208
6209 return SQLITE_OK;
6210}
6211
6212/* The conch file contains the header, host id and lock file path
6213 */
6214#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6215#define PROXY_HEADERLEN 1 /* conch file header length */
6216#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6217#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6218
6219/*
6220** Takes an open conch file, copies the contents to a new path and then moves
6221** it back. The newly created file's file descriptor is assigned to the
6222** conch file structure and finally the original conch file descriptor is
6223** closed. Returns zero if successful.
6224*/
6225static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6226 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6227 unixFile *conchFile = pCtx->conchFile;
6228 char tPath[MAXPATHLEN];
6229 char buf[PROXY_MAXCONCHLEN];
6230 char *cPath = pCtx->conchFilePath;
6231 size_t readLen = 0;
6232 size_t pathLen = 0;
6233 char errmsg[64] = "";
6234 int fd = -1;
6235 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006236 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006237
6238 /* create a new path by replace the trailing '-conch' with '-break' */
6239 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6240 if( pathLen>MAXPATHLEN || pathLen<6 ||
6241 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006242 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006243 goto end_breaklock;
6244 }
6245 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006246 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006247 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006248 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006249 goto end_breaklock;
6250 }
6251 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006252 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006253 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006254 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006255 goto end_breaklock;
6256 }
drhe562be52011-03-02 18:01:10 +00006257 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006258 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006259 goto end_breaklock;
6260 }
6261 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006262 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006263 goto end_breaklock;
6264 }
6265 rc = 0;
6266 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006267 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006268 conchFile->h = fd;
6269 conchFile->openFlags = O_RDWR | O_CREAT;
6270
6271end_breaklock:
6272 if( rc ){
6273 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006274 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006275 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006276 }
6277 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6278 }
6279 return rc;
6280}
6281
6282/* Take the requested lock on the conch file and break a stale lock if the
6283** host id matches.
6284*/
6285static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6286 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6287 unixFile *conchFile = pCtx->conchFile;
6288 int rc = SQLITE_OK;
6289 int nTries = 0;
6290 struct timespec conchModTime;
6291
drh3d4435b2011-08-26 20:55:50 +00006292 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006293 do {
6294 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6295 nTries ++;
6296 if( rc==SQLITE_BUSY ){
6297 /* If the lock failed (busy):
6298 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6299 * 2nd try: fail if the mod time changed or host id is different, wait
6300 * 10 sec and try again
6301 * 3rd try: break the lock unless the mod time has changed.
6302 */
6303 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006304 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006305 pFile->lastErrno = errno;
6306 return SQLITE_IOERR_LOCK;
6307 }
6308
6309 if( nTries==1 ){
6310 conchModTime = buf.st_mtimespec;
6311 usleep(500000); /* wait 0.5 sec and try the lock again*/
6312 continue;
6313 }
6314
6315 assert( nTries>1 );
6316 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6317 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6318 return SQLITE_BUSY;
6319 }
6320
6321 if( nTries==2 ){
6322 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006323 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006324 if( len<0 ){
6325 pFile->lastErrno = errno;
6326 return SQLITE_IOERR_LOCK;
6327 }
6328 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6329 /* don't break the lock if the host id doesn't match */
6330 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6331 return SQLITE_BUSY;
6332 }
6333 }else{
6334 /* don't break the lock on short read or a version mismatch */
6335 return SQLITE_BUSY;
6336 }
6337 usleep(10000000); /* wait 10 sec and try the lock again */
6338 continue;
6339 }
6340
6341 assert( nTries==3 );
6342 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6343 rc = SQLITE_OK;
6344 if( lockType==EXCLUSIVE_LOCK ){
6345 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6346 }
6347 if( !rc ){
6348 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6349 }
6350 }
6351 }
6352 } while( rc==SQLITE_BUSY && nTries<3 );
6353
6354 return rc;
6355}
6356
6357/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006358** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6359** lockPath means that the lockPath in the conch file will be used if the
6360** host IDs match, or a new lock path will be generated automatically
6361** and written to the conch file.
6362*/
6363static int proxyTakeConch(unixFile *pFile){
6364 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6365
drh7ed97b92010-01-20 13:07:21 +00006366 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006367 return SQLITE_OK;
6368 }else{
6369 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006370 uuid_t myHostID;
6371 int pError = 0;
6372 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006373 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006374 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006375 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006376 int createConch = 0;
6377 int hostIdMatch = 0;
6378 int readLen = 0;
6379 int tryOldLockPath = 0;
6380 int forceNewLockPath = 0;
6381
drh308c2a52010-05-14 11:30:18 +00006382 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6383 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006384
drh7ed97b92010-01-20 13:07:21 +00006385 rc = proxyGetHostID(myHostID, &pError);
6386 if( (rc&0xff)==SQLITE_IOERR ){
6387 pFile->lastErrno = pError;
6388 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006389 }
drh7ed97b92010-01-20 13:07:21 +00006390 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006391 if( rc!=SQLITE_OK ){
6392 goto end_takeconch;
6393 }
drh7ed97b92010-01-20 13:07:21 +00006394 /* read the existing conch file */
6395 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6396 if( readLen<0 ){
6397 /* I/O error: lastErrno set by seekAndRead */
6398 pFile->lastErrno = conchFile->lastErrno;
6399 rc = SQLITE_IOERR_READ;
6400 goto end_takeconch;
6401 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6402 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6403 /* a short read or version format mismatch means we need to create a new
6404 ** conch file.
6405 */
6406 createConch = 1;
6407 }
6408 /* if the host id matches and the lock path already exists in the conch
6409 ** we'll try to use the path there, if we can't open that path, we'll
6410 ** retry with a new auto-generated path
6411 */
6412 do { /* in case we need to try again for an :auto: named lock file */
6413
6414 if( !createConch && !forceNewLockPath ){
6415 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6416 PROXY_HOSTIDLEN);
6417 /* if the conch has data compare the contents */
6418 if( !pCtx->lockProxyPath ){
6419 /* for auto-named local lock file, just check the host ID and we'll
6420 ** use the local lock file path that's already in there
6421 */
6422 if( hostIdMatch ){
6423 size_t pathLen = (readLen - PROXY_PATHINDEX);
6424
6425 if( pathLen>=MAXPATHLEN ){
6426 pathLen=MAXPATHLEN-1;
6427 }
6428 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6429 lockPath[pathLen] = 0;
6430 tempLockPath = lockPath;
6431 tryOldLockPath = 1;
6432 /* create a copy of the lock path if the conch is taken */
6433 goto end_takeconch;
6434 }
6435 }else if( hostIdMatch
6436 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6437 readLen-PROXY_PATHINDEX)
6438 ){
6439 /* conch host and lock path match */
6440 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006441 }
drh7ed97b92010-01-20 13:07:21 +00006442 }
6443
6444 /* if the conch isn't writable and doesn't match, we can't take it */
6445 if( (conchFile->openFlags&O_RDWR) == 0 ){
6446 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006447 goto end_takeconch;
6448 }
drh7ed97b92010-01-20 13:07:21 +00006449
6450 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006451 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006452 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6453 tempLockPath = lockPath;
6454 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006455 }
drh7ed97b92010-01-20 13:07:21 +00006456
6457 /* update conch with host and path (this will fail if other process
6458 ** has a shared lock already), if the host id matches, use the big
6459 ** stick.
drh715ff302008-12-03 22:32:44 +00006460 */
drh7ed97b92010-01-20 13:07:21 +00006461 futimes(conchFile->h, NULL);
6462 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006463 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006464 /* We are trying for an exclusive lock but another thread in this
6465 ** same process is still holding a shared lock. */
6466 rc = SQLITE_BUSY;
6467 } else {
6468 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006469 }
drh715ff302008-12-03 22:32:44 +00006470 }else{
drh7ed97b92010-01-20 13:07:21 +00006471 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006472 }
drh7ed97b92010-01-20 13:07:21 +00006473 if( rc==SQLITE_OK ){
6474 char writeBuffer[PROXY_MAXCONCHLEN];
6475 int writeSize = 0;
6476
6477 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6478 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6479 if( pCtx->lockProxyPath!=NULL ){
6480 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6481 }else{
6482 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6483 }
6484 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006485 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006486 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6487 fsync(conchFile->h);
6488 /* If we created a new conch file (not just updated the contents of a
6489 ** valid conch file), try to match the permissions of the database
6490 */
6491 if( rc==SQLITE_OK && createConch ){
6492 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006493 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006494 if( err==0 ){
6495 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6496 S_IROTH|S_IWOTH);
6497 /* try to match the database file R/W permissions, ignore failure */
6498#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006499 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006500#else
drhff812312011-02-23 13:33:46 +00006501 do{
drhe562be52011-03-02 18:01:10 +00006502 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006503 }while( rc==(-1) && errno==EINTR );
6504 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006505 int code = errno;
6506 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6507 cmode, code, strerror(code));
6508 } else {
6509 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6510 }
6511 }else{
6512 int code = errno;
6513 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6514 err, code, strerror(code));
6515#endif
6516 }
drh715ff302008-12-03 22:32:44 +00006517 }
6518 }
drh7ed97b92010-01-20 13:07:21 +00006519 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6520
6521 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006522 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006523 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006524 int fd;
drh7ed97b92010-01-20 13:07:21 +00006525 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006526 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006527 }
6528 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006529 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006530 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006531 if( fd>=0 ){
6532 pFile->h = fd;
6533 }else{
drh9978c972010-02-23 17:36:32 +00006534 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006535 during locking */
6536 }
6537 }
6538 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6539 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6540 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6541 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6542 /* we couldn't create the proxy lock file with the old lock file path
6543 ** so try again via auto-naming
6544 */
6545 forceNewLockPath = 1;
6546 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006547 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006548 }
6549 }
6550 if( rc==SQLITE_OK ){
6551 /* Need to make a copy of path if we extracted the value
6552 ** from the conch file or the path was allocated on the stack
6553 */
6554 if( tempLockPath ){
6555 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6556 if( !pCtx->lockProxyPath ){
6557 rc = SQLITE_NOMEM;
6558 }
6559 }
6560 }
6561 if( rc==SQLITE_OK ){
6562 pCtx->conchHeld = 1;
6563
6564 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6565 afpLockingContext *afpCtx;
6566 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6567 afpCtx->dbPath = pCtx->lockProxyPath;
6568 }
6569 } else {
6570 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6571 }
drh308c2a52010-05-14 11:30:18 +00006572 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6573 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006574 return rc;
drh308c2a52010-05-14 11:30:18 +00006575 } while (1); /* in case we need to retry the :auto: lock file -
6576 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006577 }
6578}
6579
6580/*
6581** If pFile holds a lock on a conch file, then release that lock.
6582*/
6583static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006584 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006585 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6586 unixFile *conchFile; /* Name of the conch file */
6587
6588 pCtx = (proxyLockingContext *)pFile->lockingContext;
6589 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006590 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006591 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006592 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006593 if( pCtx->conchHeld>0 ){
6594 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6595 }
drh715ff302008-12-03 22:32:44 +00006596 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006597 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6598 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006599 return rc;
6600}
6601
6602/*
6603** Given the name of a database file, compute the name of its conch file.
6604** Store the conch filename in memory obtained from sqlite3_malloc().
6605** Make *pConchPath point to the new name. Return SQLITE_OK on success
6606** or SQLITE_NOMEM if unable to obtain memory.
6607**
6608** The caller is responsible for ensuring that the allocated memory
6609** space is eventually freed.
6610**
6611** *pConchPath is set to NULL if a memory allocation error occurs.
6612*/
6613static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6614 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006615 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006616 char *conchPath; /* buffer in which to construct conch name */
6617
6618 /* Allocate space for the conch filename and initialize the name to
6619 ** the name of the original database file. */
6620 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6621 if( conchPath==0 ){
6622 return SQLITE_NOMEM;
6623 }
6624 memcpy(conchPath, dbPath, len+1);
6625
6626 /* now insert a "." before the last / character */
6627 for( i=(len-1); i>=0; i-- ){
6628 if( conchPath[i]=='/' ){
6629 i++;
6630 break;
6631 }
6632 }
6633 conchPath[i]='.';
6634 while ( i<len ){
6635 conchPath[i+1]=dbPath[i];
6636 i++;
6637 }
6638
6639 /* append the "-conch" suffix to the file */
6640 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006641 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006642
6643 return SQLITE_OK;
6644}
6645
6646
6647/* Takes a fully configured proxy locking-style unix file and switches
6648** the local lock file path
6649*/
6650static int switchLockProxyPath(unixFile *pFile, const char *path) {
6651 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6652 char *oldPath = pCtx->lockProxyPath;
6653 int rc = SQLITE_OK;
6654
drh308c2a52010-05-14 11:30:18 +00006655 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006656 return SQLITE_BUSY;
6657 }
6658
6659 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6660 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6661 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6662 return SQLITE_OK;
6663 }else{
6664 unixFile *lockProxy = pCtx->lockProxy;
6665 pCtx->lockProxy=NULL;
6666 pCtx->conchHeld = 0;
6667 if( lockProxy!=NULL ){
6668 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6669 if( rc ) return rc;
6670 sqlite3_free(lockProxy);
6671 }
6672 sqlite3_free(oldPath);
6673 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6674 }
6675
6676 return rc;
6677}
6678
6679/*
6680** pFile is a file that has been opened by a prior xOpen call. dbPath
6681** is a string buffer at least MAXPATHLEN+1 characters in size.
6682**
6683** This routine find the filename associated with pFile and writes it
6684** int dbPath.
6685*/
6686static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006687#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006688 if( pFile->pMethod == &afpIoMethods ){
6689 /* afp style keeps a reference to the db path in the filePath field
6690 ** of the struct */
drhea678832008-12-10 19:26:22 +00006691 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006692 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6693 } else
drh715ff302008-12-03 22:32:44 +00006694#endif
6695 if( pFile->pMethod == &dotlockIoMethods ){
6696 /* dot lock style uses the locking context to store the dot lock
6697 ** file path */
6698 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6699 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6700 }else{
6701 /* all other styles use the locking context to store the db file path */
6702 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006703 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006704 }
6705 return SQLITE_OK;
6706}
6707
6708/*
6709** Takes an already filled in unix file and alters it so all file locking
6710** will be performed on the local proxy lock file. The following fields
6711** are preserved in the locking context so that they can be restored and
6712** the unix structure properly cleaned up at close time:
6713** ->lockingContext
6714** ->pMethod
6715*/
6716static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6717 proxyLockingContext *pCtx;
6718 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6719 char *lockPath=NULL;
6720 int rc = SQLITE_OK;
6721
drh308c2a52010-05-14 11:30:18 +00006722 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006723 return SQLITE_BUSY;
6724 }
6725 proxyGetDbPathForUnixFile(pFile, dbPath);
6726 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6727 lockPath=NULL;
6728 }else{
6729 lockPath=(char *)path;
6730 }
6731
drh308c2a52010-05-14 11:30:18 +00006732 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6733 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006734
6735 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6736 if( pCtx==0 ){
6737 return SQLITE_NOMEM;
6738 }
6739 memset(pCtx, 0, sizeof(*pCtx));
6740
6741 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6742 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006743 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6744 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6745 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6746 ** (c) the file system is read-only, then enable no-locking access.
6747 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6748 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6749 */
6750 struct statfs fsInfo;
6751 struct stat conchInfo;
6752 int goLockless = 0;
6753
drh99ab3b12011-03-02 15:09:07 +00006754 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006755 int err = errno;
6756 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6757 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6758 }
6759 }
6760 if( goLockless ){
6761 pCtx->conchHeld = -1; /* read only FS/ lockless */
6762 rc = SQLITE_OK;
6763 }
6764 }
drh715ff302008-12-03 22:32:44 +00006765 }
6766 if( rc==SQLITE_OK && lockPath ){
6767 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6768 }
6769
6770 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006771 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6772 if( pCtx->dbPath==NULL ){
6773 rc = SQLITE_NOMEM;
6774 }
6775 }
6776 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006777 /* all memory is allocated, proxys are created and assigned,
6778 ** switch the locking context and pMethod then return.
6779 */
drh715ff302008-12-03 22:32:44 +00006780 pCtx->oldLockingContext = pFile->lockingContext;
6781 pFile->lockingContext = pCtx;
6782 pCtx->pOldMethod = pFile->pMethod;
6783 pFile->pMethod = &proxyIoMethods;
6784 }else{
6785 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006786 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006787 sqlite3_free(pCtx->conchFile);
6788 }
drhd56b1212010-08-11 06:14:15 +00006789 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006790 sqlite3_free(pCtx->conchFilePath);
6791 sqlite3_free(pCtx);
6792 }
drh308c2a52010-05-14 11:30:18 +00006793 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6794 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006795 return rc;
6796}
6797
6798
6799/*
6800** This routine handles sqlite3_file_control() calls that are specific
6801** to proxy locking.
6802*/
6803static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6804 switch( op ){
6805 case SQLITE_GET_LOCKPROXYFILE: {
6806 unixFile *pFile = (unixFile*)id;
6807 if( pFile->pMethod == &proxyIoMethods ){
6808 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6809 proxyTakeConch(pFile);
6810 if( pCtx->lockProxyPath ){
6811 *(const char **)pArg = pCtx->lockProxyPath;
6812 }else{
6813 *(const char **)pArg = ":auto: (not held)";
6814 }
6815 } else {
6816 *(const char **)pArg = NULL;
6817 }
6818 return SQLITE_OK;
6819 }
6820 case SQLITE_SET_LOCKPROXYFILE: {
6821 unixFile *pFile = (unixFile*)id;
6822 int rc = SQLITE_OK;
6823 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6824 if( pArg==NULL || (const char *)pArg==0 ){
6825 if( isProxyStyle ){
6826 /* turn off proxy locking - not supported */
6827 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6828 }else{
6829 /* turn off proxy locking - already off - NOOP */
6830 rc = SQLITE_OK;
6831 }
6832 }else{
6833 const char *proxyPath = (const char *)pArg;
6834 if( isProxyStyle ){
6835 proxyLockingContext *pCtx =
6836 (proxyLockingContext*)pFile->lockingContext;
6837 if( !strcmp(pArg, ":auto:")
6838 || (pCtx->lockProxyPath &&
6839 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6840 ){
6841 rc = SQLITE_OK;
6842 }else{
6843 rc = switchLockProxyPath(pFile, proxyPath);
6844 }
6845 }else{
6846 /* turn on proxy file locking */
6847 rc = proxyTransformUnixFile(pFile, proxyPath);
6848 }
6849 }
6850 return rc;
6851 }
6852 default: {
6853 assert( 0 ); /* The call assures that only valid opcodes are sent */
6854 }
6855 }
6856 /*NOTREACHED*/
6857 return SQLITE_ERROR;
6858}
6859
6860/*
6861** Within this division (the proxying locking implementation) the procedures
6862** above this point are all utilities. The lock-related methods of the
6863** proxy-locking sqlite3_io_method object follow.
6864*/
6865
6866
6867/*
6868** This routine checks if there is a RESERVED lock held on the specified
6869** file by this or any other process. If such a lock is held, set *pResOut
6870** to a non-zero value otherwise *pResOut is set to zero. The return value
6871** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6872*/
6873static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6874 unixFile *pFile = (unixFile*)id;
6875 int rc = proxyTakeConch(pFile);
6876 if( rc==SQLITE_OK ){
6877 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006878 if( pCtx->conchHeld>0 ){
6879 unixFile *proxy = pCtx->lockProxy;
6880 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6881 }else{ /* conchHeld < 0 is lockless */
6882 pResOut=0;
6883 }
drh715ff302008-12-03 22:32:44 +00006884 }
6885 return rc;
6886}
6887
6888/*
drh308c2a52010-05-14 11:30:18 +00006889** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006890** of the following:
6891**
6892** (1) SHARED_LOCK
6893** (2) RESERVED_LOCK
6894** (3) PENDING_LOCK
6895** (4) EXCLUSIVE_LOCK
6896**
6897** Sometimes when requesting one lock state, additional lock states
6898** are inserted in between. The locking might fail on one of the later
6899** transitions leaving the lock state different from what it started but
6900** still short of its goal. The following chart shows the allowed
6901** transitions and the inserted intermediate states:
6902**
6903** UNLOCKED -> SHARED
6904** SHARED -> RESERVED
6905** SHARED -> (PENDING) -> EXCLUSIVE
6906** RESERVED -> (PENDING) -> EXCLUSIVE
6907** PENDING -> EXCLUSIVE
6908**
6909** This routine will only increase a lock. Use the sqlite3OsUnlock()
6910** routine to lower a locking level.
6911*/
drh308c2a52010-05-14 11:30:18 +00006912static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006913 unixFile *pFile = (unixFile*)id;
6914 int rc = proxyTakeConch(pFile);
6915 if( rc==SQLITE_OK ){
6916 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006917 if( pCtx->conchHeld>0 ){
6918 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006919 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6920 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006921 }else{
6922 /* conchHeld < 0 is lockless */
6923 }
drh715ff302008-12-03 22:32:44 +00006924 }
6925 return rc;
6926}
6927
6928
6929/*
drh308c2a52010-05-14 11:30:18 +00006930** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006931** must be either NO_LOCK or SHARED_LOCK.
6932**
6933** If the locking level of the file descriptor is already at or below
6934** the requested locking level, this routine is a no-op.
6935*/
drh308c2a52010-05-14 11:30:18 +00006936static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006937 unixFile *pFile = (unixFile*)id;
6938 int rc = proxyTakeConch(pFile);
6939 if( rc==SQLITE_OK ){
6940 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006941 if( pCtx->conchHeld>0 ){
6942 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006943 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6944 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006945 }else{
6946 /* conchHeld < 0 is lockless */
6947 }
drh715ff302008-12-03 22:32:44 +00006948 }
6949 return rc;
6950}
6951
6952/*
6953** Close a file that uses proxy locks.
6954*/
6955static int proxyClose(sqlite3_file *id) {
6956 if( id ){
6957 unixFile *pFile = (unixFile*)id;
6958 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6959 unixFile *lockProxy = pCtx->lockProxy;
6960 unixFile *conchFile = pCtx->conchFile;
6961 int rc = SQLITE_OK;
6962
6963 if( lockProxy ){
6964 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6965 if( rc ) return rc;
6966 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6967 if( rc ) return rc;
6968 sqlite3_free(lockProxy);
6969 pCtx->lockProxy = 0;
6970 }
6971 if( conchFile ){
6972 if( pCtx->conchHeld ){
6973 rc = proxyReleaseConch(pFile);
6974 if( rc ) return rc;
6975 }
6976 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6977 if( rc ) return rc;
6978 sqlite3_free(conchFile);
6979 }
drhd56b1212010-08-11 06:14:15 +00006980 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006981 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006982 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006983 /* restore the original locking context and pMethod then close it */
6984 pFile->lockingContext = pCtx->oldLockingContext;
6985 pFile->pMethod = pCtx->pOldMethod;
6986 sqlite3_free(pCtx);
6987 return pFile->pMethod->xClose(id);
6988 }
6989 return SQLITE_OK;
6990}
6991
6992
6993
drhd2cb50b2009-01-09 21:41:17 +00006994#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006995/*
6996** The proxy locking style is intended for use with AFP filesystems.
6997** And since AFP is only supported on MacOSX, the proxy locking is also
6998** restricted to MacOSX.
6999**
7000**
7001******************* End of the proxy lock implementation **********************
7002******************************************************************************/
7003
drh734c9862008-11-28 15:37:20 +00007004/*
danielk1977e339d652008-06-28 11:23:00 +00007005** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007006**
7007** This routine registers all VFS implementations for unix-like operating
7008** systems. This routine, and the sqlite3_os_end() routine that follows,
7009** should be the only routines in this file that are visible from other
7010** files.
drh6b9d6dd2008-12-03 19:34:47 +00007011**
7012** This routine is called once during SQLite initialization and by a
7013** single thread. The memory allocation and mutex subsystems have not
7014** necessarily been initialized when this routine is called, and so they
7015** should not be used.
drh153c62c2007-08-24 03:51:33 +00007016*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007017int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007018 /*
7019 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007020 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7021 ** to the "finder" function. (pAppData is a pointer to a pointer because
7022 ** silly C90 rules prohibit a void* from being cast to a function pointer
7023 ** and so we have to go through the intermediate pointer to avoid problems
7024 ** when compiling with -pedantic-errors on GCC.)
7025 **
7026 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007027 ** finder-function. The finder-function returns a pointer to the
7028 ** sqlite_io_methods object that implements the desired locking
7029 ** behaviors. See the division above that contains the IOMETHODS
7030 ** macro for addition information on finder-functions.
7031 **
7032 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7033 ** object. But the "autolockIoFinder" available on MacOSX does a little
7034 ** more than that; it looks at the filesystem type that hosts the
7035 ** database file and tries to choose an locking method appropriate for
7036 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007037 */
drh7708e972008-11-29 00:56:52 +00007038 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007039 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007040 sizeof(unixFile), /* szOsFile */ \
7041 MAX_PATHNAME, /* mxPathname */ \
7042 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007043 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007044 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007045 unixOpen, /* xOpen */ \
7046 unixDelete, /* xDelete */ \
7047 unixAccess, /* xAccess */ \
7048 unixFullPathname, /* xFullPathname */ \
7049 unixDlOpen, /* xDlOpen */ \
7050 unixDlError, /* xDlError */ \
7051 unixDlSym, /* xDlSym */ \
7052 unixDlClose, /* xDlClose */ \
7053 unixRandomness, /* xRandomness */ \
7054 unixSleep, /* xSleep */ \
7055 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007056 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007057 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007058 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007059 unixGetSystemCall, /* xGetSystemCall */ \
7060 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007061 }
7062
drh6b9d6dd2008-12-03 19:34:47 +00007063 /*
7064 ** All default VFSes for unix are contained in the following array.
7065 **
7066 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7067 ** by the SQLite core when the VFS is registered. So the following
7068 ** array cannot be const.
7069 */
danielk1977e339d652008-06-28 11:23:00 +00007070 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007071#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007072 UNIXVFS("unix", autolockIoFinder ),
7073#else
7074 UNIXVFS("unix", posixIoFinder ),
7075#endif
7076 UNIXVFS("unix-none", nolockIoFinder ),
7077 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007078 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007079#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007080 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007081#endif
7082#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007083 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007084#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007085 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007086#endif
chw78a13182009-04-07 05:35:03 +00007087#endif
drhd2cb50b2009-01-09 21:41:17 +00007088#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007089 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007090 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007091 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007092#endif
drh153c62c2007-08-24 03:51:33 +00007093 };
drh6b9d6dd2008-12-03 19:34:47 +00007094 unsigned int i; /* Loop counter */
7095
drh2aa5a002011-04-13 13:42:25 +00007096 /* Double-check that the aSyscall[] array has been constructed
7097 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhe1186ab2013-01-04 20:45:13 +00007098 assert( ArraySize(aSyscall)==21 );
drh2aa5a002011-04-13 13:42:25 +00007099
drh6b9d6dd2008-12-03 19:34:47 +00007100 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007101 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007102 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007103 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007104 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007105}
danielk1977e339d652008-06-28 11:23:00 +00007106
7107/*
drh6b9d6dd2008-12-03 19:34:47 +00007108** Shutdown the operating system interface.
7109**
7110** Some operating systems might need to do some cleanup in this routine,
7111** to release dynamically allocated objects. But not on unix.
7112** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007113*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007114int sqlite3_os_end(void){
7115 return SQLITE_OK;
7116}
drhdce8bdb2007-08-16 13:01:44 +00007117
danielk197729bafea2008-06-26 10:41:19 +00007118#endif /* SQLITE_OS_UNIX */