blob: 2f03c396704dc8b47a8819f65dfb8c6dbcc87a3e [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 }
danc0003312013-03-22 17:46:11 +00003473
3474 /* If the file was just truncated to a size smaller than the currently
3475 ** mapped region, reduce the effective mapping size as well. SQLite will
3476 ** use read() and write() to access data beyond this point from now on.
3477 */
3478 if( nByte<pFile->mmapSize ){
3479 pFile->mmapSize = nByte;
3480 }
drh3313b142009-11-06 04:13:18 +00003481#endif
3482
drh734c9862008-11-28 15:37:20 +00003483 return SQLITE_OK;
3484 }
3485}
3486
3487/*
3488** Determine the current size of a file in bytes
3489*/
3490static int unixFileSize(sqlite3_file *id, i64 *pSize){
3491 int rc;
3492 struct stat buf;
3493 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003494 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003495 SimulateIOError( rc=1 );
3496 if( rc!=0 ){
3497 ((unixFile*)id)->lastErrno = errno;
3498 return SQLITE_IOERR_FSTAT;
3499 }
3500 *pSize = buf.st_size;
3501
drh8af6c222010-05-14 12:43:01 +00003502 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003503 ** writes a single byte into that file in order to work around a bug
3504 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3505 ** layers, we need to report this file size as zero even though it is
3506 ** really 1. Ticket #3260.
3507 */
3508 if( *pSize==1 ) *pSize = 0;
3509
3510
3511 return SQLITE_OK;
3512}
3513
drhd2cb50b2009-01-09 21:41:17 +00003514#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003515/*
3516** Handler for proxy-locking file-control verbs. Defined below in the
3517** proxying locking division.
3518*/
3519static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003520#endif
drh715ff302008-12-03 22:32:44 +00003521
dan502019c2010-07-28 14:26:17 +00003522/*
3523** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003524** file-control operation. Enlarge the database to nBytes in size
3525** (rounded up to the next chunk-size). If the database is already
3526** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003527*/
3528static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003529 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003530 i64 nSize; /* Required file size */
3531 struct stat buf; /* Used to hold return values of fstat() */
3532
drh99ab3b12011-03-02 15:09:07 +00003533 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003534
3535 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3536 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003537
dan502019c2010-07-28 14:26:17 +00003538#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003539 /* The code below is handling the return value of osFallocate()
3540 ** correctly. posix_fallocate() is defined to "returns zero on success,
3541 ** or an error number on failure". See the manpage for details. */
3542 int err;
drhff812312011-02-23 13:33:46 +00003543 do{
dan661d71a2011-03-30 19:08:03 +00003544 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3545 }while( err==EINTR );
3546 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003547#else
3548 /* If the OS does not have posix_fallocate(), fake it. First use
3549 ** ftruncate() to set the file size, then write a single byte to
3550 ** the last byte in each block within the extended region. This
3551 ** is the same technique used by glibc to implement posix_fallocate()
3552 ** on systems that do not have a real fallocate() system call.
3553 */
3554 int nBlk = buf.st_blksize; /* File-system block size */
3555 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003556
drhff812312011-02-23 13:33:46 +00003557 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003558 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003559 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003560 }
3561 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003562 while( iWrite<nSize ){
3563 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3564 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003565 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003566 }
dan502019c2010-07-28 14:26:17 +00003567#endif
3568 }
3569 }
3570
3571 return SQLITE_OK;
3572}
danielk1977ad94b582007-08-20 06:44:22 +00003573
danielk1977e3026632004-06-22 11:29:02 +00003574/*
drhf12b3f62011-12-21 14:42:29 +00003575** If *pArg is inititially negative then this is a query. Set *pArg to
3576** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3577**
3578** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3579*/
3580static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3581 if( *pArg<0 ){
3582 *pArg = (pFile->ctrlFlags & mask)!=0;
3583 }else if( (*pArg)==0 ){
3584 pFile->ctrlFlags &= ~mask;
3585 }else{
3586 pFile->ctrlFlags |= mask;
3587 }
3588}
3589
drh696b33e2012-12-06 19:01:42 +00003590/* Forward declaration */
3591static int unixGetTempname(int nBuf, char *zBuf);
3592
drhf12b3f62011-12-21 14:42:29 +00003593/*
drh9e33c2c2007-08-31 18:34:59 +00003594** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003595*/
drhcc6bb3e2007-08-31 16:11:35 +00003596static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003597 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003598 switch( op ){
3599 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003600 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003601 return SQLITE_OK;
3602 }
drh7708e972008-11-29 00:56:52 +00003603 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003604 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003605 return SQLITE_OK;
3606 }
dan6e09d692010-07-27 18:34:15 +00003607 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003608 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003609 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003610 }
drh9ff27ec2010-05-19 19:26:05 +00003611 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003612 int rc;
3613 SimulateIOErrorBenign(1);
3614 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3615 SimulateIOErrorBenign(0);
3616 return rc;
drhf0b190d2011-07-26 16:03:07 +00003617 }
3618 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003619 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3620 return SQLITE_OK;
3621 }
drhcb15f352011-12-23 01:04:17 +00003622 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3623 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003624 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003625 }
drhde60fc22011-12-14 17:53:36 +00003626 case SQLITE_FCNTL_VFSNAME: {
3627 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3628 return SQLITE_OK;
3629 }
drh696b33e2012-12-06 19:01:42 +00003630 case SQLITE_FCNTL_TEMPFILENAME: {
3631 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3632 if( zTFile ){
3633 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3634 *(char**)pArg = zTFile;
3635 }
3636 return SQLITE_OK;
3637 }
danb2d3de32013-03-14 18:34:37 +00003638 case SQLITE_FCNTL_GETFD: {
3639 *(int*)pArg = pFile->h;
3640 return SQLITE_OK;
3641 }
drhd3d8c042012-05-29 17:02:40 +00003642#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003643 /* The pager calls this method to signal that it has done
3644 ** a rollback and that the database is therefore unchanged and
3645 ** it hence it is OK for the transaction change counter to be
3646 ** unchanged.
3647 */
3648 case SQLITE_FCNTL_DB_UNCHANGED: {
3649 ((unixFile*)id)->dbUpdate = 0;
3650 return SQLITE_OK;
3651 }
3652#endif
drhd2cb50b2009-01-09 21:41:17 +00003653#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003654 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003655 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003656 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003657 }
drhd2cb50b2009-01-09 21:41:17 +00003658#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003659 }
drh0b52b7d2011-01-26 19:46:22 +00003660 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003661}
3662
3663/*
danielk1977a3d4c882007-03-23 10:08:38 +00003664** Return the sector size in bytes of the underlying block device for
3665** the specified file. This is almost always 512 bytes, but may be
3666** larger for some devices.
3667**
3668** SQLite code assumes this function cannot fail. It also assumes that
3669** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003670** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003671** same for both.
3672*/
drh537dddf2012-10-26 13:46:24 +00003673#ifndef __QNXNTO__
3674static int unixSectorSize(sqlite3_file *NotUsed){
3675 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003676 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003677}
drh537dddf2012-10-26 13:46:24 +00003678#endif
3679
3680/*
3681** The following version of unixSectorSize() is optimized for QNX.
3682*/
3683#ifdef __QNXNTO__
3684#include <sys/dcmd_blk.h>
3685#include <sys/statvfs.h>
3686static int unixSectorSize(sqlite3_file *id){
3687 unixFile *pFile = (unixFile*)id;
3688 if( pFile->sectorSize == 0 ){
3689 struct statvfs fsInfo;
3690
3691 /* Set defaults for non-supported filesystems */
3692 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3693 pFile->deviceCharacteristics = 0;
3694 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3695 return pFile->sectorSize;
3696 }
3697
3698 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3699 pFile->sectorSize = fsInfo.f_bsize;
3700 pFile->deviceCharacteristics =
3701 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3702 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3703 ** the write succeeds */
3704 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3705 ** so it is ordered */
3706 0;
3707 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3708 pFile->sectorSize = fsInfo.f_bsize;
3709 pFile->deviceCharacteristics =
3710 /* etfs cluster size writes are atomic */
3711 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3712 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3713 ** the write succeeds */
3714 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3715 ** so it is ordered */
3716 0;
3717 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3718 pFile->sectorSize = fsInfo.f_bsize;
3719 pFile->deviceCharacteristics =
3720 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3721 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3722 ** the write succeeds */
3723 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3724 ** so it is ordered */
3725 0;
3726 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
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 if( strstr(fsInfo.f_basetype, "dos") ){
3735 pFile->sectorSize = fsInfo.f_bsize;
3736 pFile->deviceCharacteristics =
3737 /* full bitset of atomics from max sector size and smaller */
3738 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3739 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3740 ** so it is ordered */
3741 0;
3742 }else{
3743 pFile->deviceCharacteristics =
3744 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3745 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3746 ** the write succeeds */
3747 0;
3748 }
3749 }
3750 /* Last chance verification. If the sector size isn't a multiple of 512
3751 ** then it isn't valid.*/
3752 if( pFile->sectorSize % 512 != 0 ){
3753 pFile->deviceCharacteristics = 0;
3754 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3755 }
3756 return pFile->sectorSize;
3757}
3758#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003759
danielk197790949c22007-08-17 16:50:38 +00003760/*
drhf12b3f62011-12-21 14:42:29 +00003761** Return the device characteristics for the file.
3762**
drhcb15f352011-12-23 01:04:17 +00003763** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3764** However, that choice is contraversial since technically the underlying
3765** file system does not always provide powersafe overwrites. (In other
3766** words, after a power-loss event, parts of the file that were never
3767** written might end up being altered.) However, non-PSOW behavior is very,
3768** very rare. And asserting PSOW makes a large reduction in the amount
3769** of required I/O for journaling, since a lot of padding is eliminated.
3770** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3771** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003772*/
drhf12b3f62011-12-21 14:42:29 +00003773static int unixDeviceCharacteristics(sqlite3_file *id){
3774 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003775 int rc = 0;
3776#ifdef __QNXNTO__
3777 if( p->sectorSize==0 ) unixSectorSize(id);
3778 rc = p->deviceCharacteristics;
3779#endif
drhcb15f352011-12-23 01:04:17 +00003780 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003781 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003782 }
drh537dddf2012-10-26 13:46:24 +00003783 return rc;
danielk197762079062007-08-15 17:08:46 +00003784}
3785
drhd9e5c4f2010-05-12 18:01:39 +00003786#ifndef SQLITE_OMIT_WAL
3787
3788
3789/*
drhd91c68f2010-05-14 14:52:25 +00003790** Object used to represent an shared memory buffer.
3791**
3792** When multiple threads all reference the same wal-index, each thread
3793** has its own unixShm object, but they all point to a single instance
3794** of this unixShmNode object. In other words, each wal-index is opened
3795** only once per process.
3796**
3797** Each unixShmNode object is connected to a single unixInodeInfo object.
3798** We could coalesce this object into unixInodeInfo, but that would mean
3799** every open file that does not use shared memory (in other words, most
3800** open files) would have to carry around this extra information. So
3801** the unixInodeInfo object contains a pointer to this unixShmNode object
3802** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003803**
3804** unixMutexHeld() must be true when creating or destroying
3805** this object or while reading or writing the following fields:
3806**
3807** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003808**
3809** The following fields are read-only after the object is created:
3810**
3811** fid
3812** zFilename
3813**
drhd91c68f2010-05-14 14:52:25 +00003814** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003815** unixMutexHeld() is true when reading or writing any other field
3816** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003817*/
drhd91c68f2010-05-14 14:52:25 +00003818struct unixShmNode {
3819 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003820 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003821 char *zFilename; /* Name of the mmapped file */
3822 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003823 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003824 u16 nRegion; /* Size of array apRegion */
3825 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003826 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003827 int nRef; /* Number of unixShm objects pointing to this */
3828 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003829#ifdef SQLITE_DEBUG
3830 u8 exclMask; /* Mask of exclusive locks held */
3831 u8 sharedMask; /* Mask of shared locks held */
3832 u8 nextShmId; /* Next available unixShm.id value */
3833#endif
3834};
3835
3836/*
drhd9e5c4f2010-05-12 18:01:39 +00003837** Structure used internally by this VFS to record the state of an
3838** open shared memory connection.
3839**
drhd91c68f2010-05-14 14:52:25 +00003840** The following fields are initialized when this object is created and
3841** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003842**
drhd91c68f2010-05-14 14:52:25 +00003843** unixShm.pFile
3844** unixShm.id
3845**
3846** All other fields are read/write. The unixShm.pFile->mutex must be held
3847** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003848*/
3849struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003850 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3851 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003852 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003853 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003854 u16 sharedMask; /* Mask of shared locks held */
3855 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003856};
3857
3858/*
drhd9e5c4f2010-05-12 18:01:39 +00003859** Constants used for locking
3860*/
drhbd9676c2010-06-23 17:58:38 +00003861#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003862#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003863
drhd9e5c4f2010-05-12 18:01:39 +00003864/*
drh73b64e42010-05-30 19:55:15 +00003865** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003866**
3867** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3868** otherwise.
3869*/
3870static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003871 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3872 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003873 int ofst, /* First byte of the locking range */
3874 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003875){
3876 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003877 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003878
drhd91c68f2010-05-14 14:52:25 +00003879 /* Access to the unixShmNode object is serialized by the caller */
3880 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003881
drh73b64e42010-05-30 19:55:15 +00003882 /* Shared locks never span more than one byte */
3883 assert( n==1 || lockType!=F_RDLCK );
3884
3885 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003886 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003887
drh3cb93392011-03-12 18:10:44 +00003888 if( pShmNode->h>=0 ){
3889 /* Initialize the locking parameters */
3890 memset(&f, 0, sizeof(f));
3891 f.l_type = lockType;
3892 f.l_whence = SEEK_SET;
3893 f.l_start = ofst;
3894 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003895
drh3cb93392011-03-12 18:10:44 +00003896 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3897 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3898 }
drhd9e5c4f2010-05-12 18:01:39 +00003899
3900 /* Update the global lock state and do debug tracing */
3901#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003902 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003903 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003904 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003905 if( rc==SQLITE_OK ){
3906 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003907 OSTRACE(("unlock %d ok", ofst));
3908 pShmNode->exclMask &= ~mask;
3909 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003910 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003911 OSTRACE(("read-lock %d ok", ofst));
3912 pShmNode->exclMask &= ~mask;
3913 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003914 }else{
3915 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003916 OSTRACE(("write-lock %d ok", ofst));
3917 pShmNode->exclMask |= mask;
3918 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003919 }
3920 }else{
3921 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003922 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003923 }else if( lockType==F_RDLCK ){
3924 OSTRACE(("read-lock failed"));
3925 }else{
3926 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003927 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003928 }
3929 }
drh20e1f082010-05-31 16:10:12 +00003930 OSTRACE((" - afterwards %03x,%03x\n",
3931 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003932 }
drhd9e5c4f2010-05-12 18:01:39 +00003933#endif
3934
3935 return rc;
3936}
3937
drhd9e5c4f2010-05-12 18:01:39 +00003938
3939/*
drhd91c68f2010-05-14 14:52:25 +00003940** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003941**
3942** This is not a VFS shared-memory method; it is a utility function called
3943** by VFS shared-memory methods.
3944*/
drhd91c68f2010-05-14 14:52:25 +00003945static void unixShmPurge(unixFile *pFd){
3946 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003947 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003948 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003949 int i;
drhd91c68f2010-05-14 14:52:25 +00003950 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003951 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003952 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003953 if( p->h>=0 ){
3954 munmap(p->apRegion[i], p->szRegion);
3955 }else{
3956 sqlite3_free(p->apRegion[i]);
3957 }
dan13a3cb82010-06-11 19:04:21 +00003958 }
dan18801912010-06-14 14:07:50 +00003959 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003960 if( p->h>=0 ){
3961 robust_close(pFd, p->h, __LINE__);
3962 p->h = -1;
3963 }
drhd91c68f2010-05-14 14:52:25 +00003964 p->pInode->pShmNode = 0;
3965 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003966 }
3967}
3968
3969/*
danda9fe0c2010-07-13 18:44:03 +00003970** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003971** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003972**
drh7234c6d2010-06-19 15:10:09 +00003973** The file used to implement shared-memory is in the same directory
3974** as the open database file and has the same name as the open database
3975** file with the "-shm" suffix added. For example, if the database file
3976** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003977** for shared memory will be called "/home/user1/config.db-shm".
3978**
3979** Another approach to is to use files in /dev/shm or /dev/tmp or an
3980** some other tmpfs mount. But if a file in a different directory
3981** from the database file is used, then differing access permissions
3982** or a chroot() might cause two different processes on the same
3983** database to end up using different files for shared memory -
3984** meaning that their memory would not really be shared - resulting
3985** in database corruption. Nevertheless, this tmpfs file usage
3986** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3987** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3988** option results in an incompatible build of SQLite; builds of SQLite
3989** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3990** same database file at the same time, database corruption will likely
3991** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3992** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003993**
3994** When opening a new shared-memory file, if no other instances of that
3995** file are currently open, in this process or in other processes, then
3996** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003997**
3998** If the original database file (pDbFd) is using the "unix-excl" VFS
3999** that means that an exclusive lock is held on the database file and
4000** that no other processes are able to read or write the database. In
4001** that case, we do not really need shared memory. No shared memory
4002** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004003*/
danda9fe0c2010-07-13 18:44:03 +00004004static int unixOpenSharedMemory(unixFile *pDbFd){
4005 struct unixShm *p = 0; /* The connection to be opened */
4006 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4007 int rc; /* Result code */
4008 unixInodeInfo *pInode; /* The inode of fd */
4009 char *zShmFilename; /* Name of the file used for SHM */
4010 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004011
danda9fe0c2010-07-13 18:44:03 +00004012 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004013 p = sqlite3_malloc( sizeof(*p) );
4014 if( p==0 ) return SQLITE_NOMEM;
4015 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004016 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004017
danda9fe0c2010-07-13 18:44:03 +00004018 /* Check to see if a unixShmNode object already exists. Reuse an existing
4019 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004020 */
4021 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004022 pInode = pDbFd->pInode;
4023 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004024 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004025 struct stat sStat; /* fstat() info for database file */
4026
4027 /* Call fstat() to figure out the permissions on the database file. If
4028 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004029 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004030 */
drh3cb93392011-03-12 18:10:44 +00004031 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004032 rc = SQLITE_IOERR_FSTAT;
4033 goto shm_open_err;
4034 }
4035
drha4ced192010-07-15 18:32:40 +00004036#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004037 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004038#else
drh52bcde02012-01-03 14:50:45 +00004039 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004040#endif
drh7234c6d2010-06-19 15:10:09 +00004041 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004042 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004043 rc = SQLITE_NOMEM;
4044 goto shm_open_err;
4045 }
drh9cb5a0d2012-01-05 21:19:54 +00004046 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004047 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004048#ifdef SQLITE_SHM_DIRECTORY
4049 sqlite3_snprintf(nShmFilename, zShmFilename,
4050 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4051 (u32)sStat.st_ino, (u32)sStat.st_dev);
4052#else
drh7234c6d2010-06-19 15:10:09 +00004053 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004054 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004055#endif
drhd91c68f2010-05-14 14:52:25 +00004056 pShmNode->h = -1;
4057 pDbFd->pInode->pShmNode = pShmNode;
4058 pShmNode->pInode = pDbFd->pInode;
4059 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4060 if( pShmNode->mutex==0 ){
4061 rc = SQLITE_NOMEM;
4062 goto shm_open_err;
4063 }
drhd9e5c4f2010-05-12 18:01:39 +00004064
drh3cb93392011-03-12 18:10:44 +00004065 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004066 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004067 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004068 openFlags = O_RDONLY;
4069 pShmNode->isReadonly = 1;
4070 }
4071 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004072 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004073 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4074 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004075 }
drhac7c3ac2012-02-11 19:23:48 +00004076
4077 /* If this process is running as root, make sure that the SHM file
4078 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004079 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004080 */
drhed466822012-05-31 13:10:49 +00004081 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004082
4083 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004084 ** If not, truncate the file to zero length.
4085 */
4086 rc = SQLITE_OK;
4087 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4088 if( robust_ftruncate(pShmNode->h, 0) ){
4089 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004090 }
4091 }
drh66dfec8b2011-06-01 20:01:49 +00004092 if( rc==SQLITE_OK ){
4093 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4094 }
4095 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004096 }
drhd9e5c4f2010-05-12 18:01:39 +00004097 }
4098
drhd91c68f2010-05-14 14:52:25 +00004099 /* Make the new connection a child of the unixShmNode */
4100 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004101#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004102 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004103#endif
drhd91c68f2010-05-14 14:52:25 +00004104 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004105 pDbFd->pShm = p;
4106 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004107
4108 /* The reference count on pShmNode has already been incremented under
4109 ** the cover of the unixEnterMutex() mutex and the pointer from the
4110 ** new (struct unixShm) object to the pShmNode has been set. All that is
4111 ** left to do is to link the new object into the linked list starting
4112 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4113 ** mutex.
4114 */
4115 sqlite3_mutex_enter(pShmNode->mutex);
4116 p->pNext = pShmNode->pFirst;
4117 pShmNode->pFirst = p;
4118 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004119 return SQLITE_OK;
4120
4121 /* Jump here on any error */
4122shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004123 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004124 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004125 unixLeaveMutex();
4126 return rc;
4127}
4128
4129/*
danda9fe0c2010-07-13 18:44:03 +00004130** This function is called to obtain a pointer to region iRegion of the
4131** shared-memory associated with the database file fd. Shared-memory regions
4132** are numbered starting from zero. Each shared-memory region is szRegion
4133** bytes in size.
4134**
4135** If an error occurs, an error code is returned and *pp is set to NULL.
4136**
4137** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4138** region has not been allocated (by any client, including one running in a
4139** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4140** bExtend is non-zero and the requested shared-memory region has not yet
4141** been allocated, it is allocated by this function.
4142**
4143** If the shared-memory region has already been allocated or is allocated by
4144** this call as described above, then it is mapped into this processes
4145** address space (if it is not already), *pp is set to point to the mapped
4146** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004147*/
danda9fe0c2010-07-13 18:44:03 +00004148static int unixShmMap(
4149 sqlite3_file *fd, /* Handle open on database file */
4150 int iRegion, /* Region to retrieve */
4151 int szRegion, /* Size of regions */
4152 int bExtend, /* True to extend file if necessary */
4153 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004154){
danda9fe0c2010-07-13 18:44:03 +00004155 unixFile *pDbFd = (unixFile*)fd;
4156 unixShm *p;
4157 unixShmNode *pShmNode;
4158 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004159
danda9fe0c2010-07-13 18:44:03 +00004160 /* If the shared-memory file has not yet been opened, open it now. */
4161 if( pDbFd->pShm==0 ){
4162 rc = unixOpenSharedMemory(pDbFd);
4163 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004164 }
drhd9e5c4f2010-05-12 18:01:39 +00004165
danda9fe0c2010-07-13 18:44:03 +00004166 p = pDbFd->pShm;
4167 pShmNode = p->pShmNode;
4168 sqlite3_mutex_enter(pShmNode->mutex);
4169 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004170 assert( pShmNode->pInode==pDbFd->pInode );
4171 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4172 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004173
4174 if( pShmNode->nRegion<=iRegion ){
4175 char **apNew; /* New apRegion[] array */
4176 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4177 struct stat sStat; /* Used by fstat() */
4178
4179 pShmNode->szRegion = szRegion;
4180
drh3cb93392011-03-12 18:10:44 +00004181 if( pShmNode->h>=0 ){
4182 /* The requested region is not mapped into this processes address space.
4183 ** Check to see if it has been allocated (i.e. if the wal-index file is
4184 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004185 */
drh3cb93392011-03-12 18:10:44 +00004186 if( osFstat(pShmNode->h, &sStat) ){
4187 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004188 goto shmpage_out;
4189 }
drh3cb93392011-03-12 18:10:44 +00004190
4191 if( sStat.st_size<nByte ){
4192 /* The requested memory region does not exist. If bExtend is set to
4193 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4194 **
4195 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4196 ** the requested memory region.
4197 */
4198 if( !bExtend ) goto shmpage_out;
drh0fbb50e2012-11-13 10:54:12 +00004199#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
4200 if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
4201 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
4202 pShmNode->zFilename);
4203 goto shmpage_out;
4204 }
4205#else
drh3cb93392011-03-12 18:10:44 +00004206 if( robust_ftruncate(pShmNode->h, nByte) ){
4207 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4208 pShmNode->zFilename);
4209 goto shmpage_out;
4210 }
drh0fbb50e2012-11-13 10:54:12 +00004211#endif
drh3cb93392011-03-12 18:10:44 +00004212 }
danda9fe0c2010-07-13 18:44:03 +00004213 }
4214
4215 /* Map the requested memory region into this processes address space. */
4216 apNew = (char **)sqlite3_realloc(
4217 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4218 );
4219 if( !apNew ){
4220 rc = SQLITE_IOERR_NOMEM;
4221 goto shmpage_out;
4222 }
4223 pShmNode->apRegion = apNew;
4224 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004225 void *pMem;
4226 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004227 pMem = mmap(0, szRegion,
4228 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004229 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004230 );
4231 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004232 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004233 goto shmpage_out;
4234 }
4235 }else{
4236 pMem = sqlite3_malloc(szRegion);
4237 if( pMem==0 ){
4238 rc = SQLITE_NOMEM;
4239 goto shmpage_out;
4240 }
4241 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004242 }
4243 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4244 pShmNode->nRegion++;
4245 }
4246 }
4247
4248shmpage_out:
4249 if( pShmNode->nRegion>iRegion ){
4250 *pp = pShmNode->apRegion[iRegion];
4251 }else{
4252 *pp = 0;
4253 }
drh66dfec8b2011-06-01 20:01:49 +00004254 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004255 sqlite3_mutex_leave(pShmNode->mutex);
4256 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004257}
4258
4259/*
drhd9e5c4f2010-05-12 18:01:39 +00004260** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004261**
4262** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4263** different here than in posix. In xShmLock(), one can go from unlocked
4264** to shared and back or from unlocked to exclusive and back. But one may
4265** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004266*/
4267static int unixShmLock(
4268 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004269 int ofst, /* First lock to acquire or release */
4270 int n, /* Number of locks to acquire or release */
4271 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004272){
drh73b64e42010-05-30 19:55:15 +00004273 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4274 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4275 unixShm *pX; /* For looping over all siblings */
4276 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4277 int rc = SQLITE_OK; /* Result code */
4278 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004279
drhd91c68f2010-05-14 14:52:25 +00004280 assert( pShmNode==pDbFd->pInode->pShmNode );
4281 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004282 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004283 assert( n>=1 );
4284 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4285 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4286 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4287 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4288 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004289 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4290 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004291
drhc99597c2010-05-31 01:41:15 +00004292 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004293 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004294 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004295 if( flags & SQLITE_SHM_UNLOCK ){
4296 u16 allMask = 0; /* Mask of locks held by siblings */
4297
4298 /* See if any siblings hold this same lock */
4299 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4300 if( pX==p ) continue;
4301 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4302 allMask |= pX->sharedMask;
4303 }
4304
4305 /* Unlock the system-level locks */
4306 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004307 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004308 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004309 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004310 }
drh73b64e42010-05-30 19:55:15 +00004311
4312 /* Undo the local locks */
4313 if( rc==SQLITE_OK ){
4314 p->exclMask &= ~mask;
4315 p->sharedMask &= ~mask;
4316 }
4317 }else if( flags & SQLITE_SHM_SHARED ){
4318 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4319
4320 /* Find out which shared locks are already held by sibling connections.
4321 ** If any sibling already holds an exclusive lock, go ahead and return
4322 ** SQLITE_BUSY.
4323 */
4324 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004325 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004326 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004327 break;
4328 }
4329 allShared |= pX->sharedMask;
4330 }
4331
4332 /* Get shared locks at the system level, if necessary */
4333 if( rc==SQLITE_OK ){
4334 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004335 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004336 }else{
drh73b64e42010-05-30 19:55:15 +00004337 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004338 }
drhd9e5c4f2010-05-12 18:01:39 +00004339 }
drh73b64e42010-05-30 19:55:15 +00004340
4341 /* Get the local shared locks */
4342 if( rc==SQLITE_OK ){
4343 p->sharedMask |= mask;
4344 }
4345 }else{
4346 /* Make sure no sibling connections hold locks that will block this
4347 ** lock. If any do, return SQLITE_BUSY right away.
4348 */
4349 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004350 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4351 rc = SQLITE_BUSY;
4352 break;
4353 }
4354 }
4355
4356 /* Get the exclusive locks at the system level. Then if successful
4357 ** also mark the local connection as being locked.
4358 */
4359 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004360 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004361 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004362 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004363 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004364 }
drhd9e5c4f2010-05-12 18:01:39 +00004365 }
4366 }
drhd91c68f2010-05-14 14:52:25 +00004367 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004368 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4369 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004370 return rc;
4371}
4372
drh286a2882010-05-20 23:51:06 +00004373/*
4374** Implement a memory barrier or memory fence on shared memory.
4375**
4376** All loads and stores begun before the barrier must complete before
4377** any load or store begun after the barrier.
4378*/
4379static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004380 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004381){
drhff828942010-06-26 21:34:06 +00004382 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004383 unixEnterMutex();
4384 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004385}
4386
dan18801912010-06-14 14:07:50 +00004387/*
danda9fe0c2010-07-13 18:44:03 +00004388** Close a connection to shared-memory. Delete the underlying
4389** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004390**
4391** If there is no shared memory associated with the connection then this
4392** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004393*/
danda9fe0c2010-07-13 18:44:03 +00004394static int unixShmUnmap(
4395 sqlite3_file *fd, /* The underlying database file */
4396 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004397){
danda9fe0c2010-07-13 18:44:03 +00004398 unixShm *p; /* The connection to be closed */
4399 unixShmNode *pShmNode; /* The underlying shared-memory file */
4400 unixShm **pp; /* For looping over sibling connections */
4401 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004402
danda9fe0c2010-07-13 18:44:03 +00004403 pDbFd = (unixFile*)fd;
4404 p = pDbFd->pShm;
4405 if( p==0 ) return SQLITE_OK;
4406 pShmNode = p->pShmNode;
4407
4408 assert( pShmNode==pDbFd->pInode->pShmNode );
4409 assert( pShmNode->pInode==pDbFd->pInode );
4410
4411 /* Remove connection p from the set of connections associated
4412 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004413 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004414 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4415 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004416
danda9fe0c2010-07-13 18:44:03 +00004417 /* Free the connection p */
4418 sqlite3_free(p);
4419 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004420 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004421
4422 /* If pShmNode->nRef has reached 0, then close the underlying
4423 ** shared-memory file, too */
4424 unixEnterMutex();
4425 assert( pShmNode->nRef>0 );
4426 pShmNode->nRef--;
4427 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004428 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004429 unixShmPurge(pDbFd);
4430 }
4431 unixLeaveMutex();
4432
4433 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004434}
drh286a2882010-05-20 23:51:06 +00004435
danda9fe0c2010-07-13 18:44:03 +00004436
drhd9e5c4f2010-05-12 18:01:39 +00004437#else
drh6b017cc2010-06-14 18:01:46 +00004438# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004439# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004440# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004441# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004442#endif /* #ifndef SQLITE_OMIT_WAL */
4443
drh734c9862008-11-28 15:37:20 +00004444/*
dand306e1a2013-03-20 18:25:49 +00004445** Arguments x and y are both integers. Argument y must be a power of 2.
4446** Round x up to the nearest integer multiple of y. For example:
4447**
4448** ROUNDUP(0, 8) -> 0
4449** ROUNDUP(13, 8) -> 16
4450** ROUNDUP(32, 8) -> 32
4451*/
4452#define ROUNDUP(x,y) (((x)+y-1)&~(y-1))
4453
4454/*
dan5d8a1372013-03-19 19:28:06 +00004455** Map, remap or unmap part of the database file.
4456*/
4457static int unixMremap(
4458 sqlite3_file *fd, /* Main database file */
daneb97b292013-03-20 14:26:59 +00004459 int flags, /* Mask of SQLITE_MREMAP_XXX flags */
dan5d8a1372013-03-19 19:28:06 +00004460 sqlite3_int64 iOff, /* Offset to start mapping at */
4461 sqlite3_int64 nOld, /* Size of old mapping, or zero */
4462 sqlite3_int64 nNew, /* Size of new mapping, or zero */
4463 void **ppMap /* IN/OUT: Old/new mappings */
4464){
4465 unixFile *p = (unixFile *)fd; /* The underlying database file */
4466 int rc = SQLITE_OK; /* Return code */
4467 void *pNew = 0; /* New mapping */
dand306e1a2013-03-20 18:25:49 +00004468 i64 nNewRnd; /* nNew rounded up */
4469 i64 nOldRnd; /* nOld rounded up */
dan5d8a1372013-03-19 19:28:06 +00004470
4471 assert( iOff==0 );
danc0003312013-03-22 17:46:11 +00004472 /* assert( p->mmapSize==nOld ); */
dan6101d502013-03-22 08:58:38 +00004473 assert( p->pMapRegion==0 || p->pMapRegion==(*ppMap) );
daneb97b292013-03-20 14:26:59 +00004474
4475 /* If the SQLITE_MREMAP_EXTEND flag is set, then the size of the requested
4476 ** mapping (nNew bytes) may be greater than the size of the database file.
4477 ** If this is the case, extend the file on disk using ftruncate(). */
4478 assert( nNew>0 || (flags & SQLITE_MREMAP_EXTEND)==0 );
4479 if( flags & SQLITE_MREMAP_EXTEND ){
4480 struct stat statbuf; /* Low-level file information */
4481 rc = osFstat(p->h, &statbuf);
4482 if( rc==SQLITE_OK && nNew>statbuf.st_size ){
4483 rc = robust_ftruncate(p->h, nNew);
4484 }
4485 if( rc!=SQLITE_OK ) return rc;
4486 }
4487
dand306e1a2013-03-20 18:25:49 +00004488 /* According to some sources, the effect of changing the size of the
4489 ** underlying file on mapped regions that correspond to the added or
4490 ** removed pages is undefined. However, there is reason to believe that
4491 ** on modern platforms like Linux or OSX, things just work. For example,
4492 ** it is possible to create a mapping larger than the file on disk and
4493 ** extend the file on disk later on.
4494 **
danc71b45e2013-03-21 14:47:47 +00004495 ** Exploit this on Linux and OSX to reduce the number of munmap()/mmap()
4496 ** calls required if the file size is changing. In this case all mappings
4497 ** are rounded up to the nearest 4MB. And if a new mapping is requested
4498 ** that has the same rounded size as an old mapping, the old mapping can
4499 ** be reused as is. */
4500#if defined(__APPLE__) || defined(__linux__)
dand306e1a2013-03-20 18:25:49 +00004501 nNewRnd = ROUNDUP(nNew, 4096*1024);
4502 nOldRnd = ROUNDUP(nOld, 4096*1024);
4503#else
4504 nNewRnd = ROUNDUP(nNew, 4096*1);
4505 nOldRnd = ROUNDUP(nOld, 4096*1);
4506#endif
4507
4508 /* On OSX or Linux, reuse the old mapping if it is the right size. */
4509#if defined(__APPLE__) || defined(__linux__)
4510 if( nNewRnd==nOldRnd ){
dan6101d502013-03-22 08:58:38 +00004511 VVA_ONLY( p->mmapSize = nNew; )
dand306e1a2013-03-20 18:25:49 +00004512 return SQLITE_OK;
4513 }
4514#endif
4515
dand306e1a2013-03-20 18:25:49 +00004516 /* If we get this far, unmap any old mapping. */
4517 if( nOldRnd!=0 ){
dan5d8a1372013-03-19 19:28:06 +00004518 void *pOld = *ppMap;
dand306e1a2013-03-20 18:25:49 +00004519 munmap(pOld, nOldRnd);
dan6101d502013-03-22 08:58:38 +00004520 VVA_ONLY( p->mmapSize = 0; p->pMapRegion = 0; );
dan5d8a1372013-03-19 19:28:06 +00004521 }
4522
dand306e1a2013-03-20 18:25:49 +00004523 /* And, if required, use mmap() to create a new mapping. */
4524 if( nNewRnd>0 ){
dan5d8a1372013-03-19 19:28:06 +00004525 int flags = PROT_READ;
4526 if( (p->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
dand306e1a2013-03-20 18:25:49 +00004527 pNew = mmap(0, nNewRnd, flags, MAP_SHARED, p->h, iOff);
dan5d8a1372013-03-19 19:28:06 +00004528 if( pNew==MAP_FAILED ){
4529 pNew = 0;
dan6101d502013-03-22 08:58:38 +00004530 VVA_ONLY( p->mmapSize = 0; p->pMapRegion = 0; )
daneb97b292013-03-20 14:26:59 +00004531 rc = SQLITE_IOERR_MREMAP;
dan6101d502013-03-22 08:58:38 +00004532 }else{
4533 VVA_ONLY( p->mmapSize = nNew; p->pMapRegion = pNew; )
dan5d8a1372013-03-19 19:28:06 +00004534 }
4535 }
4536
4537 *ppMap = pNew;
4538 return rc;
4539}
4540
4541/*
drh734c9862008-11-28 15:37:20 +00004542** Here ends the implementation of all sqlite3_file methods.
4543**
4544********************** End sqlite3_file Methods *******************************
4545******************************************************************************/
4546
4547/*
drh6b9d6dd2008-12-03 19:34:47 +00004548** This division contains definitions of sqlite3_io_methods objects that
4549** implement various file locking strategies. It also contains definitions
4550** of "finder" functions. A finder-function is used to locate the appropriate
4551** sqlite3_io_methods object for a particular database file. The pAppData
4552** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4553** the correct finder-function for that VFS.
4554**
4555** Most finder functions return a pointer to a fixed sqlite3_io_methods
4556** object. The only interesting finder-function is autolockIoFinder, which
4557** looks at the filesystem type and tries to guess the best locking
4558** strategy from that.
4559**
drh1875f7a2008-12-08 18:19:17 +00004560** For finder-funtion F, two objects are created:
4561**
4562** (1) The real finder-function named "FImpt()".
4563**
dane946c392009-08-22 11:39:46 +00004564** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004565**
4566**
4567** A pointer to the F pointer is used as the pAppData value for VFS
4568** objects. We have to do this instead of letting pAppData point
4569** directly at the finder-function since C90 rules prevent a void*
4570** from be cast into a function pointer.
4571**
drh6b9d6dd2008-12-03 19:34:47 +00004572**
drh7708e972008-11-29 00:56:52 +00004573** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004574**
drh7708e972008-11-29 00:56:52 +00004575** * A constant sqlite3_io_methods object call METHOD that has locking
4576** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4577**
4578** * An I/O method finder function called FINDER that returns a pointer
4579** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004580*/
drhd9e5c4f2010-05-12 18:01:39 +00004581#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004582static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004583 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004584 CLOSE, /* xClose */ \
4585 unixRead, /* xRead */ \
4586 unixWrite, /* xWrite */ \
4587 unixTruncate, /* xTruncate */ \
4588 unixSync, /* xSync */ \
4589 unixFileSize, /* xFileSize */ \
4590 LOCK, /* xLock */ \
4591 UNLOCK, /* xUnlock */ \
4592 CKLOCK, /* xCheckReservedLock */ \
4593 unixFileControl, /* xFileControl */ \
4594 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004595 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004596 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004597 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004598 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004599 unixShmUnmap, /* xShmUnmap */ \
4600 unixMremap, /* xMremap */ \
drh7708e972008-11-29 00:56:52 +00004601}; \
drh0c2694b2009-09-03 16:23:44 +00004602static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4603 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004604 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004605} \
drh0c2694b2009-09-03 16:23:44 +00004606static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004607 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004608
4609/*
4610** Here are all of the sqlite3_io_methods objects for each of the
4611** locking strategies. Functions that return pointers to these methods
4612** are also created.
4613*/
4614IOMETHODS(
4615 posixIoFinder, /* Finder function name */
4616 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004617 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004618 unixClose, /* xClose method */
4619 unixLock, /* xLock method */
4620 unixUnlock, /* xUnlock method */
4621 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004622)
drh7708e972008-11-29 00:56:52 +00004623IOMETHODS(
4624 nolockIoFinder, /* Finder function name */
4625 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004626 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004627 nolockClose, /* xClose method */
4628 nolockLock, /* xLock method */
4629 nolockUnlock, /* xUnlock method */
4630 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004631)
drh7708e972008-11-29 00:56:52 +00004632IOMETHODS(
4633 dotlockIoFinder, /* Finder function name */
4634 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004635 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004636 dotlockClose, /* xClose method */
4637 dotlockLock, /* xLock method */
4638 dotlockUnlock, /* xUnlock method */
4639 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004640)
drh7708e972008-11-29 00:56:52 +00004641
chw78a13182009-04-07 05:35:03 +00004642#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004643IOMETHODS(
4644 flockIoFinder, /* Finder function name */
4645 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004646 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004647 flockClose, /* xClose method */
4648 flockLock, /* xLock method */
4649 flockUnlock, /* xUnlock method */
4650 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004651)
drh7708e972008-11-29 00:56:52 +00004652#endif
4653
drh6c7d5c52008-11-21 20:32:33 +00004654#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004655IOMETHODS(
4656 semIoFinder, /* Finder function name */
4657 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004658 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004659 semClose, /* xClose method */
4660 semLock, /* xLock method */
4661 semUnlock, /* xUnlock method */
4662 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004663)
aswiftaebf4132008-11-21 00:10:35 +00004664#endif
drh7708e972008-11-29 00:56:52 +00004665
drhd2cb50b2009-01-09 21:41:17 +00004666#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004667IOMETHODS(
4668 afpIoFinder, /* Finder function name */
4669 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004670 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004671 afpClose, /* xClose method */
4672 afpLock, /* xLock method */
4673 afpUnlock, /* xUnlock method */
4674 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004675)
drh715ff302008-12-03 22:32:44 +00004676#endif
4677
4678/*
4679** The proxy locking method is a "super-method" in the sense that it
4680** opens secondary file descriptors for the conch and lock files and
4681** it uses proxy, dot-file, AFP, and flock() locking methods on those
4682** secondary files. For this reason, the division that implements
4683** proxy locking is located much further down in the file. But we need
4684** to go ahead and define the sqlite3_io_methods and finder function
4685** for proxy locking here. So we forward declare the I/O methods.
4686*/
drhd2cb50b2009-01-09 21:41:17 +00004687#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004688static int proxyClose(sqlite3_file*);
4689static int proxyLock(sqlite3_file*, int);
4690static int proxyUnlock(sqlite3_file*, int);
4691static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004692IOMETHODS(
4693 proxyIoFinder, /* Finder function name */
4694 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004695 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004696 proxyClose, /* xClose method */
4697 proxyLock, /* xLock method */
4698 proxyUnlock, /* xUnlock method */
4699 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004700)
aswiftaebf4132008-11-21 00:10:35 +00004701#endif
drh7708e972008-11-29 00:56:52 +00004702
drh7ed97b92010-01-20 13:07:21 +00004703/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4704#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4705IOMETHODS(
4706 nfsIoFinder, /* Finder function name */
4707 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004708 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004709 unixClose, /* xClose method */
4710 unixLock, /* xLock method */
4711 nfsUnlock, /* xUnlock method */
4712 unixCheckReservedLock /* xCheckReservedLock method */
4713)
4714#endif
drh7708e972008-11-29 00:56:52 +00004715
drhd2cb50b2009-01-09 21:41:17 +00004716#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004717/*
drh6b9d6dd2008-12-03 19:34:47 +00004718** This "finder" function attempts to determine the best locking strategy
4719** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004720** object that implements that strategy.
4721**
4722** This is for MacOSX only.
4723*/
drh1875f7a2008-12-08 18:19:17 +00004724static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004725 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004726 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004727){
4728 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004729 const char *zFilesystem; /* Filesystem type name */
4730 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004731 } aMap[] = {
4732 { "hfs", &posixIoMethods },
4733 { "ufs", &posixIoMethods },
4734 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004735 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004736 { "webdav", &nolockIoMethods },
4737 { 0, 0 }
4738 };
4739 int i;
4740 struct statfs fsInfo;
4741 struct flock lockInfo;
4742
4743 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004744 /* If filePath==NULL that means we are dealing with a transient file
4745 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004746 return &nolockIoMethods;
4747 }
4748 if( statfs(filePath, &fsInfo) != -1 ){
4749 if( fsInfo.f_flags & MNT_RDONLY ){
4750 return &nolockIoMethods;
4751 }
4752 for(i=0; aMap[i].zFilesystem; i++){
4753 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4754 return aMap[i].pMethods;
4755 }
4756 }
4757 }
4758
4759 /* Default case. Handles, amongst others, "nfs".
4760 ** Test byte-range lock using fcntl(). If the call succeeds,
4761 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004762 */
drh7708e972008-11-29 00:56:52 +00004763 lockInfo.l_len = 1;
4764 lockInfo.l_start = 0;
4765 lockInfo.l_whence = SEEK_SET;
4766 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004767 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004768 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4769 return &nfsIoMethods;
4770 } else {
4771 return &posixIoMethods;
4772 }
drh7708e972008-11-29 00:56:52 +00004773 }else{
4774 return &dotlockIoMethods;
4775 }
4776}
drh0c2694b2009-09-03 16:23:44 +00004777static const sqlite3_io_methods
4778 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004779
drhd2cb50b2009-01-09 21:41:17 +00004780#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004781
chw78a13182009-04-07 05:35:03 +00004782#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4783/*
4784** This "finder" function attempts to determine the best locking strategy
4785** for the database file "filePath". It then returns the sqlite3_io_methods
4786** object that implements that strategy.
4787**
4788** This is for VXWorks only.
4789*/
4790static const sqlite3_io_methods *autolockIoFinderImpl(
4791 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004792 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004793){
4794 struct flock lockInfo;
4795
4796 if( !filePath ){
4797 /* If filePath==NULL that means we are dealing with a transient file
4798 ** that does not need to be locked. */
4799 return &nolockIoMethods;
4800 }
4801
4802 /* Test if fcntl() is supported and use POSIX style locks.
4803 ** Otherwise fall back to the named semaphore method.
4804 */
4805 lockInfo.l_len = 1;
4806 lockInfo.l_start = 0;
4807 lockInfo.l_whence = SEEK_SET;
4808 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004809 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004810 return &posixIoMethods;
4811 }else{
4812 return &semIoMethods;
4813 }
4814}
drh0c2694b2009-09-03 16:23:44 +00004815static const sqlite3_io_methods
4816 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004817
4818#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4819
drh7708e972008-11-29 00:56:52 +00004820/*
4821** An abstract type for a pointer to a IO method finder function:
4822*/
drh0c2694b2009-09-03 16:23:44 +00004823typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004824
aswiftaebf4132008-11-21 00:10:35 +00004825
drh734c9862008-11-28 15:37:20 +00004826/****************************************************************************
4827**************************** sqlite3_vfs methods ****************************
4828**
4829** This division contains the implementation of methods on the
4830** sqlite3_vfs object.
4831*/
4832
danielk1977a3d4c882007-03-23 10:08:38 +00004833/*
danielk1977e339d652008-06-28 11:23:00 +00004834** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004835*/
4836static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004837 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004838 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004839 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004840 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004841 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004842){
drh7708e972008-11-29 00:56:52 +00004843 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004844 unixFile *pNew = (unixFile *)pId;
4845 int rc = SQLITE_OK;
4846
drh8af6c222010-05-14 12:43:01 +00004847 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004848
dan00157392010-10-05 11:33:15 +00004849 /* Usually the path zFilename should not be a relative pathname. The
4850 ** exception is when opening the proxy "conch" file in builds that
4851 ** include the special Apple locking styles.
4852 */
dan00157392010-10-05 11:33:15 +00004853#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004854 assert( zFilename==0 || zFilename[0]=='/'
4855 || pVfs->pAppData==(void*)&autolockIoFinder );
4856#else
4857 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004858#endif
dan00157392010-10-05 11:33:15 +00004859
drhb07028f2011-10-14 21:49:18 +00004860 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004861 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004862
drh308c2a52010-05-14 11:30:18 +00004863 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004864 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004865 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004866 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004867 pNew->ctrlFlags = (u8)ctrlFlags;
dan6101d502013-03-22 08:58:38 +00004868 VVA_ONLY( pNew->mmapSize = 0; )
drhc02a43a2012-01-10 23:18:38 +00004869 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4870 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004871 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004872 }
drh503a6862013-03-01 01:07:17 +00004873 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00004874 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004875 }
drh339eb0b2008-03-07 15:34:11 +00004876
drh6c7d5c52008-11-21 20:32:33 +00004877#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004878 pNew->pId = vxworksFindFileId(zFilename);
4879 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004880 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004881 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004882 }
4883#endif
4884
drhc02a43a2012-01-10 23:18:38 +00004885 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004886 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004887 }else{
drh0c2694b2009-09-03 16:23:44 +00004888 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004889#if SQLITE_ENABLE_LOCKING_STYLE
4890 /* Cache zFilename in the locking context (AFP and dotlock override) for
4891 ** proxyLock activation is possible (remote proxy is based on db name)
4892 ** zFilename remains valid until file is closed, to support */
4893 pNew->lockingContext = (void*)zFilename;
4894#endif
drhda0e7682008-07-30 15:27:54 +00004895 }
danielk1977e339d652008-06-28 11:23:00 +00004896
drh7ed97b92010-01-20 13:07:21 +00004897 if( pLockingStyle == &posixIoMethods
4898#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4899 || pLockingStyle == &nfsIoMethods
4900#endif
4901 ){
drh7708e972008-11-29 00:56:52 +00004902 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004903 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004904 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004905 /* If an error occured in findInodeInfo(), close the file descriptor
4906 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004907 ** in two scenarios:
4908 **
4909 ** (a) A call to fstat() failed.
4910 ** (b) A malloc failed.
4911 **
4912 ** Scenario (b) may only occur if the process is holding no other
4913 ** file descriptors open on the same file. If there were other file
4914 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004915 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004916 ** handle h - as it is guaranteed that no posix locks will be released
4917 ** by doing so.
4918 **
4919 ** If scenario (a) caused the error then things are not so safe. The
4920 ** implicit assumption here is that if fstat() fails, things are in
4921 ** such bad shape that dropping a lock or two doesn't matter much.
4922 */
drh0e9365c2011-03-02 02:08:13 +00004923 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004924 h = -1;
4925 }
drh7708e972008-11-29 00:56:52 +00004926 unixLeaveMutex();
4927 }
danielk1977e339d652008-06-28 11:23:00 +00004928
drhd2cb50b2009-01-09 21:41:17 +00004929#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004930 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004931 /* AFP locking uses the file path so it needs to be included in
4932 ** the afpLockingContext.
4933 */
4934 afpLockingContext *pCtx;
4935 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4936 if( pCtx==0 ){
4937 rc = SQLITE_NOMEM;
4938 }else{
4939 /* NB: zFilename exists and remains valid until the file is closed
4940 ** according to requirement F11141. So we do not need to make a
4941 ** copy of the filename. */
4942 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004943 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004944 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004945 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004946 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004947 if( rc!=SQLITE_OK ){
4948 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004949 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004950 h = -1;
4951 }
drh7708e972008-11-29 00:56:52 +00004952 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004953 }
drh7708e972008-11-29 00:56:52 +00004954 }
4955#endif
danielk1977e339d652008-06-28 11:23:00 +00004956
drh7708e972008-11-29 00:56:52 +00004957 else if( pLockingStyle == &dotlockIoMethods ){
4958 /* Dotfile locking uses the file path so it needs to be included in
4959 ** the dotlockLockingContext
4960 */
4961 char *zLockFile;
4962 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004963 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004964 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004965 zLockFile = (char *)sqlite3_malloc(nFilename);
4966 if( zLockFile==0 ){
4967 rc = SQLITE_NOMEM;
4968 }else{
4969 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004970 }
drh7708e972008-11-29 00:56:52 +00004971 pNew->lockingContext = zLockFile;
4972 }
danielk1977e339d652008-06-28 11:23:00 +00004973
drh6c7d5c52008-11-21 20:32:33 +00004974#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004975 else if( pLockingStyle == &semIoMethods ){
4976 /* Named semaphore locking uses the file path so it needs to be
4977 ** included in the semLockingContext
4978 */
4979 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004980 rc = findInodeInfo(pNew, &pNew->pInode);
4981 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4982 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004983 int n;
drh2238dcc2009-08-27 17:56:20 +00004984 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004985 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004986 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004987 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004988 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4989 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004990 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004991 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004992 }
chw97185482008-11-17 08:05:31 +00004993 }
drh7708e972008-11-29 00:56:52 +00004994 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004995 }
drh7708e972008-11-29 00:56:52 +00004996#endif
aswift5b1a2562008-08-22 00:22:35 +00004997
4998 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004999#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005000 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005001 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005002 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005003 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00005004 isDelete = 0;
5005 }
drhc02a43a2012-01-10 23:18:38 +00005006 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005007#endif
danielk1977e339d652008-06-28 11:23:00 +00005008 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005009 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005010 }else{
drh7708e972008-11-29 00:56:52 +00005011 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005012 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00005013 }
danielk1977e339d652008-06-28 11:23:00 +00005014 return rc;
drh054889e2005-11-30 03:20:31 +00005015}
drh9c06c952005-11-26 00:25:00 +00005016
danielk1977ad94b582007-08-20 06:44:22 +00005017/*
drh8b3cf822010-06-01 21:02:51 +00005018** Return the name of a directory in which to put temporary files.
5019** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005020*/
drh7234c6d2010-06-19 15:10:09 +00005021static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005022 static const char *azDirs[] = {
5023 0,
aswiftaebf4132008-11-21 00:10:35 +00005024 0,
danielk197717b90b52008-06-06 11:11:25 +00005025 "/var/tmp",
5026 "/usr/tmp",
5027 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005028 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005029 };
drh8b3cf822010-06-01 21:02:51 +00005030 unsigned int i;
5031 struct stat buf;
5032 const char *zDir = 0;
5033
5034 azDirs[0] = sqlite3_temp_directory;
5035 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005036 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005037 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005038 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005039 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005040 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005041 break;
5042 }
5043 return zDir;
5044}
5045
5046/*
5047** Create a temporary file name in zBuf. zBuf must be allocated
5048** by the calling process and must be big enough to hold at least
5049** pVfs->mxPathname bytes.
5050*/
5051static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005052 static const unsigned char zChars[] =
5053 "abcdefghijklmnopqrstuvwxyz"
5054 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5055 "0123456789";
drh41022642008-11-21 00:24:42 +00005056 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005057 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005058
5059 /* It's odd to simulate an io-error here, but really this is just
5060 ** using the io-error infrastructure to test that SQLite handles this
5061 ** function failing.
5062 */
5063 SimulateIOError( return SQLITE_IOERR );
5064
drh7234c6d2010-06-19 15:10:09 +00005065 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005066 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005067
5068 /* Check that the output buffer is large enough for the temporary file
5069 ** name. If it is not, return SQLITE_ERROR.
5070 */
drhc02a43a2012-01-10 23:18:38 +00005071 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005072 return SQLITE_ERROR;
5073 }
5074
5075 do{
drhc02a43a2012-01-10 23:18:38 +00005076 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005077 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005078 sqlite3_randomness(15, &zBuf[j]);
5079 for(i=0; i<15; i++, j++){
5080 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5081 }
5082 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005083 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005084 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005085 return SQLITE_OK;
5086}
5087
drhd2cb50b2009-01-09 21:41:17 +00005088#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005089/*
5090** Routine to transform a unixFile into a proxy-locking unixFile.
5091** Implementation in the proxy-lock division, but used by unixOpen()
5092** if SQLITE_PREFER_PROXY_LOCKING is defined.
5093*/
5094static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005095#endif
drhc66d5b62008-12-03 22:48:32 +00005096
dan08da86a2009-08-21 17:18:03 +00005097/*
5098** Search for an unused file descriptor that was opened on the database
5099** file (not a journal or master-journal file) identified by pathname
5100** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5101** argument to this function.
5102**
5103** Such a file descriptor may exist if a database connection was closed
5104** but the associated file descriptor could not be closed because some
5105** other file descriptor open on the same file is holding a file-lock.
5106** Refer to comments in the unixClose() function and the lengthy comment
5107** describing "Posix Advisory Locking" at the start of this file for
5108** further details. Also, ticket #4018.
5109**
5110** If a suitable file descriptor is found, then it is returned. If no
5111** such file descriptor is located, -1 is returned.
5112*/
dane946c392009-08-22 11:39:46 +00005113static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5114 UnixUnusedFd *pUnused = 0;
5115
5116 /* Do not search for an unused file descriptor on vxworks. Not because
5117 ** vxworks would not benefit from the change (it might, we're not sure),
5118 ** but because no way to test it is currently available. It is better
5119 ** not to risk breaking vxworks support for the sake of such an obscure
5120 ** feature. */
5121#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005122 struct stat sStat; /* Results of stat() call */
5123
5124 /* A stat() call may fail for various reasons. If this happens, it is
5125 ** almost certain that an open() call on the same path will also fail.
5126 ** For this reason, if an error occurs in the stat() call here, it is
5127 ** ignored and -1 is returned. The caller will try to open a new file
5128 ** descriptor on the same path, fail, and return an error to SQLite.
5129 **
5130 ** Even if a subsequent open() call does succeed, the consequences of
5131 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005132 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005133 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005134
5135 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005136 pInode = inodeList;
5137 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5138 || pInode->fileId.ino!=sStat.st_ino) ){
5139 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005140 }
drh8af6c222010-05-14 12:43:01 +00005141 if( pInode ){
dane946c392009-08-22 11:39:46 +00005142 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005143 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005144 pUnused = *pp;
5145 if( pUnused ){
5146 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005147 }
5148 }
5149 unixLeaveMutex();
5150 }
dane946c392009-08-22 11:39:46 +00005151#endif /* if !OS_VXWORKS */
5152 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005153}
danielk197717b90b52008-06-06 11:11:25 +00005154
5155/*
danddb0ac42010-07-14 14:48:58 +00005156** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005157** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005158** and a value suitable for passing as the third argument to open(2) is
5159** written to *pMode. If an IO error occurs, an SQLite error code is
5160** returned and the value of *pMode is not modified.
5161**
drh8c815d12012-02-13 20:16:37 +00005162** In most cases cases, this routine sets *pMode to 0, which will become
5163** an indication to robust_open() to create the file using
5164** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5165** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005166** this function queries the file-system for the permissions on the
5167** corresponding database file and sets *pMode to this value. Whenever
5168** possible, WAL and journal files are created using the same permissions
5169** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005170**
5171** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5172** original filename is unavailable. But 8_3_NAMES is only used for
5173** FAT filesystems and permissions do not matter there, so just use
5174** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005175*/
5176static int findCreateFileMode(
5177 const char *zPath, /* Path of file (possibly) being created */
5178 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005179 mode_t *pMode, /* OUT: Permissions to open file with */
5180 uid_t *pUid, /* OUT: uid to set on the file */
5181 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005182){
5183 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005184 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005185 *pUid = 0;
5186 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005187 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005188 char zDb[MAX_PATHNAME+1]; /* Database file path */
5189 int nDb; /* Number of valid bytes in zDb */
5190 struct stat sStat; /* Output of stat() on database file */
5191
dana0c989d2010-11-05 18:07:37 +00005192 /* zPath is a path to a WAL or journal file. The following block derives
5193 ** the path to the associated database file from zPath. This block handles
5194 ** the following naming conventions:
5195 **
5196 ** "<path to db>-journal"
5197 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005198 ** "<path to db>-journalNN"
5199 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005200 **
drhd337c5b2011-10-20 18:23:35 +00005201 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005202 ** used by the test_multiplex.c module.
5203 */
5204 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005205#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005206 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005207 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005208#else
5209 while( zPath[nDb]!='-' ){
5210 assert( nDb>0 );
5211 assert( zPath[nDb]!='\n' );
5212 nDb--;
5213 }
5214#endif
danddb0ac42010-07-14 14:48:58 +00005215 memcpy(zDb, zPath, nDb);
5216 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005217
drh58384f12011-07-28 00:14:45 +00005218 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005219 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005220 *pUid = sStat.st_uid;
5221 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005222 }else{
5223 rc = SQLITE_IOERR_FSTAT;
5224 }
5225 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5226 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005227 }
5228 return rc;
5229}
5230
5231/*
danielk1977ad94b582007-08-20 06:44:22 +00005232** Open the file zPath.
5233**
danielk1977b4b47412007-08-17 15:53:36 +00005234** Previously, the SQLite OS layer used three functions in place of this
5235** one:
5236**
5237** sqlite3OsOpenReadWrite();
5238** sqlite3OsOpenReadOnly();
5239** sqlite3OsOpenExclusive();
5240**
5241** These calls correspond to the following combinations of flags:
5242**
5243** ReadWrite() -> (READWRITE | CREATE)
5244** ReadOnly() -> (READONLY)
5245** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5246**
5247** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5248** true, the file was configured to be automatically deleted when the
5249** file handle closed. To achieve the same effect using this new
5250** interface, add the DELETEONCLOSE flag to those specified above for
5251** OpenExclusive().
5252*/
5253static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005254 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5255 const char *zPath, /* Pathname of file to be opened */
5256 sqlite3_file *pFile, /* The file descriptor to be filled in */
5257 int flags, /* Input flags to control the opening */
5258 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005259){
dan08da86a2009-08-21 17:18:03 +00005260 unixFile *p = (unixFile *)pFile;
5261 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005262 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005263 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005264 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005265 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005266 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005267
5268 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5269 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5270 int isCreate = (flags & SQLITE_OPEN_CREATE);
5271 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5272 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005273#if SQLITE_ENABLE_LOCKING_STYLE
5274 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5275#endif
drh3d4435b2011-08-26 20:55:50 +00005276#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5277 struct statfs fsInfo;
5278#endif
danielk1977b4b47412007-08-17 15:53:36 +00005279
danielk1977fee2d252007-08-18 10:59:19 +00005280 /* If creating a master or main-file journal, this function will open
5281 ** a file-descriptor on the directory too. The first time unixSync()
5282 ** is called the directory file descriptor will be fsync()ed and close()d.
5283 */
drh0059eae2011-08-08 23:48:40 +00005284 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005285 eType==SQLITE_OPEN_MASTER_JOURNAL
5286 || eType==SQLITE_OPEN_MAIN_JOURNAL
5287 || eType==SQLITE_OPEN_WAL
5288 ));
danielk1977fee2d252007-08-18 10:59:19 +00005289
danielk197717b90b52008-06-06 11:11:25 +00005290 /* If argument zPath is a NULL pointer, this function is required to open
5291 ** a temporary file. Use this buffer to store the file name in.
5292 */
drhc02a43a2012-01-10 23:18:38 +00005293 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005294 const char *zName = zPath;
5295
danielk1977fee2d252007-08-18 10:59:19 +00005296 /* Check the following statements are true:
5297 **
5298 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5299 ** (b) if CREATE is set, then READWRITE must also be set, and
5300 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005301 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005302 */
danielk1977b4b47412007-08-17 15:53:36 +00005303 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005304 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005305 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005306 assert(isDelete==0 || isCreate);
5307
danddb0ac42010-07-14 14:48:58 +00005308 /* The main DB, main journal, WAL file and master journal are never
5309 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005310 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5311 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5312 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005313 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005314
danielk1977fee2d252007-08-18 10:59:19 +00005315 /* Assert that the upper layer has set one of the "file-type" flags. */
5316 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5317 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5318 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005319 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005320 );
5321
dan08da86a2009-08-21 17:18:03 +00005322 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005323
dan08da86a2009-08-21 17:18:03 +00005324 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005325 UnixUnusedFd *pUnused;
5326 pUnused = findReusableFd(zName, flags);
5327 if( pUnused ){
5328 fd = pUnused->fd;
5329 }else{
dan6aa657f2009-08-24 18:57:58 +00005330 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005331 if( !pUnused ){
5332 return SQLITE_NOMEM;
5333 }
5334 }
5335 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005336
5337 /* Database filenames are double-zero terminated if they are not
5338 ** URIs with parameters. Hence, they can always be passed into
5339 ** sqlite3_uri_parameter(). */
5340 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5341
dan08da86a2009-08-21 17:18:03 +00005342 }else if( !zName ){
5343 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005344 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005345 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005346 if( rc!=SQLITE_OK ){
5347 return rc;
5348 }
5349 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005350
5351 /* Generated temporary filenames are always double-zero terminated
5352 ** for use by sqlite3_uri_parameter(). */
5353 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005354 }
5355
dan08da86a2009-08-21 17:18:03 +00005356 /* Determine the value of the flags parameter passed to POSIX function
5357 ** open(). These must be calculated even if open() is not called, as
5358 ** they may be stored as part of the file handle and used by the
5359 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005360 if( isReadonly ) openFlags |= O_RDONLY;
5361 if( isReadWrite ) openFlags |= O_RDWR;
5362 if( isCreate ) openFlags |= O_CREAT;
5363 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5364 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005365
danielk1977b4b47412007-08-17 15:53:36 +00005366 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005367 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005368 uid_t uid; /* Userid for the file */
5369 gid_t gid; /* Groupid for the file */
5370 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005371 if( rc!=SQLITE_OK ){
5372 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005373 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005374 return rc;
5375 }
drhad4f1e52011-03-04 15:43:57 +00005376 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005377 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005378 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5379 /* Failed to open the file for read/write access. Try read-only. */
5380 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005381 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005382 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005383 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005384 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005385 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005386 }
5387 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005388 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005389 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005390 }
drhac7c3ac2012-02-11 19:23:48 +00005391
5392 /* If this process is running as root and if creating a new rollback
5393 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005394 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005395 */
5396 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005397 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005398 }
danielk1977b4b47412007-08-17 15:53:36 +00005399 }
dan08da86a2009-08-21 17:18:03 +00005400 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005401 if( pOutFlags ){
5402 *pOutFlags = flags;
5403 }
5404
dane946c392009-08-22 11:39:46 +00005405 if( p->pUnused ){
5406 p->pUnused->fd = fd;
5407 p->pUnused->flags = flags;
5408 }
5409
danielk1977b4b47412007-08-17 15:53:36 +00005410 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005411#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005412 zPath = zName;
5413#else
drh036ac7f2011-08-08 23:18:05 +00005414 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005415#endif
danielk1977b4b47412007-08-17 15:53:36 +00005416 }
drh41022642008-11-21 00:24:42 +00005417#if SQLITE_ENABLE_LOCKING_STYLE
5418 else{
dan08da86a2009-08-21 17:18:03 +00005419 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005420 }
5421#endif
5422
drhda0e7682008-07-30 15:27:54 +00005423 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005424
drh7ed97b92010-01-20 13:07:21 +00005425
5426#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005427 if( fstatfs(fd, &fsInfo) == -1 ){
5428 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005429 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005430 return SQLITE_IOERR_ACCESS;
5431 }
5432 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5433 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5434 }
5435#endif
drhc02a43a2012-01-10 23:18:38 +00005436
5437 /* Set up appropriate ctrlFlags */
5438 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5439 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5440 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5441 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5442 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5443
drh7ed97b92010-01-20 13:07:21 +00005444#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005445#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005446 isAutoProxy = 1;
5447#endif
5448 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005449 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5450 int useProxy = 0;
5451
dan08da86a2009-08-21 17:18:03 +00005452 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5453 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005454 if( envforce!=NULL ){
5455 useProxy = atoi(envforce)>0;
5456 }else{
aswiftaebf4132008-11-21 00:10:35 +00005457 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005458 /* In theory, the close(fd) call is sub-optimal. If the file opened
5459 ** with fd is a database file, and there are other connections open
5460 ** on that file that are currently holding advisory locks on it,
5461 ** then the call to close() will cancel those locks. In practice,
5462 ** we're assuming that statfs() doesn't fail very often. At least
5463 ** not while other file descriptors opened by the same process on
5464 ** the same file are working. */
5465 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005466 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005467 rc = SQLITE_IOERR_ACCESS;
5468 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005469 }
5470 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5471 }
5472 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005473 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005474 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005475 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005476 if( rc!=SQLITE_OK ){
5477 /* Use unixClose to clean up the resources added in fillInUnixFile
5478 ** and clear all the structure's references. Specifically,
5479 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5480 */
5481 unixClose(pFile);
5482 return rc;
5483 }
aswiftaebf4132008-11-21 00:10:35 +00005484 }
dane946c392009-08-22 11:39:46 +00005485 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005486 }
5487 }
5488#endif
5489
drhc02a43a2012-01-10 23:18:38 +00005490 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5491
dane946c392009-08-22 11:39:46 +00005492open_finished:
5493 if( rc!=SQLITE_OK ){
5494 sqlite3_free(p->pUnused);
5495 }
5496 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005497}
5498
dane946c392009-08-22 11:39:46 +00005499
danielk1977b4b47412007-08-17 15:53:36 +00005500/*
danielk1977fee2d252007-08-18 10:59:19 +00005501** Delete the file at zPath. If the dirSync argument is true, fsync()
5502** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005503*/
drh6b9d6dd2008-12-03 19:34:47 +00005504static int unixDelete(
5505 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5506 const char *zPath, /* Name of file to be deleted */
5507 int dirSync /* If true, fsync() directory after deleting file */
5508){
danielk1977fee2d252007-08-18 10:59:19 +00005509 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005510 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005511 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005512 if( osUnlink(zPath)==(-1) ){
5513 if( errno==ENOENT ){
5514 rc = SQLITE_IOERR_DELETE_NOENT;
5515 }else{
drhb4308162012-11-09 21:40:02 +00005516 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005517 }
drhb4308162012-11-09 21:40:02 +00005518 return rc;
drh5d4feff2010-07-14 01:45:22 +00005519 }
danielk1977d39fa702008-10-16 13:27:40 +00005520#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005521 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005522 int fd;
drh90315a22011-08-10 01:52:12 +00005523 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005524 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005525#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005526 if( fsync(fd)==-1 )
5527#else
5528 if( fsync(fd) )
5529#endif
5530 {
dane18d4952011-02-21 11:46:24 +00005531 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005532 }
drh0e9365c2011-03-02 02:08:13 +00005533 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005534 }else if( rc==SQLITE_CANTOPEN ){
5535 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005536 }
5537 }
danielk1977d138dd82008-10-15 16:02:48 +00005538#endif
danielk1977fee2d252007-08-18 10:59:19 +00005539 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005540}
5541
danielk197790949c22007-08-17 16:50:38 +00005542/*
5543** Test the existance of or access permissions of file zPath. The
5544** test performed depends on the value of flags:
5545**
5546** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5547** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5548** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5549**
5550** Otherwise return 0.
5551*/
danielk1977861f7452008-06-05 11:39:11 +00005552static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005553 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5554 const char *zPath, /* Path of the file to examine */
5555 int flags, /* What do we want to learn about the zPath file? */
5556 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005557){
rse25c0d1a2007-09-20 08:38:14 +00005558 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005559 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005560 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005561 switch( flags ){
5562 case SQLITE_ACCESS_EXISTS:
5563 amode = F_OK;
5564 break;
5565 case SQLITE_ACCESS_READWRITE:
5566 amode = W_OK|R_OK;
5567 break;
drh50d3f902007-08-27 21:10:36 +00005568 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005569 amode = R_OK;
5570 break;
5571
5572 default:
5573 assert(!"Invalid flags argument");
5574 }
drh99ab3b12011-03-02 15:09:07 +00005575 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005576 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5577 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005578 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005579 *pResOut = 0;
5580 }
5581 }
danielk1977861f7452008-06-05 11:39:11 +00005582 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005583}
5584
danielk1977b4b47412007-08-17 15:53:36 +00005585
5586/*
5587** Turn a relative pathname into a full pathname. The relative path
5588** is stored as a nul-terminated string in the buffer pointed to by
5589** zPath.
5590**
5591** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5592** (in this case, MAX_PATHNAME bytes). The full-path is written to
5593** this buffer before returning.
5594*/
danielk1977adfb9b02007-09-17 07:02:56 +00005595static int unixFullPathname(
5596 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5597 const char *zPath, /* Possibly relative input path */
5598 int nOut, /* Size of output buffer in bytes */
5599 char *zOut /* Output buffer */
5600){
danielk1977843e65f2007-09-01 16:16:15 +00005601
5602 /* It's odd to simulate an io-error here, but really this is just
5603 ** using the io-error infrastructure to test that SQLite handles this
5604 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005605 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005606 */
5607 SimulateIOError( return SQLITE_ERROR );
5608
drh153c62c2007-08-24 03:51:33 +00005609 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005610 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005611
drh3c7f2dc2007-12-06 13:26:20 +00005612 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005613 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005614 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005615 }else{
5616 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005617 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005618 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005619 }
drhea678832008-12-10 19:26:22 +00005620 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005621 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005622 }
5623 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005624}
5625
drh0ccebe72005-06-07 22:22:50 +00005626
drh761df872006-12-21 01:29:22 +00005627#ifndef SQLITE_OMIT_LOAD_EXTENSION
5628/*
5629** Interfaces for opening a shared library, finding entry points
5630** within the shared library, and closing the shared library.
5631*/
5632#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005633static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5634 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005635 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5636}
danielk197795c8a542007-09-01 06:51:27 +00005637
5638/*
5639** SQLite calls this function immediately after a call to unixDlSym() or
5640** unixDlOpen() fails (returns a null pointer). If a more detailed error
5641** message is available, it is written to zBufOut. If no error message
5642** is available, zBufOut is left unmodified and SQLite uses a default
5643** error message.
5644*/
danielk1977397d65f2008-11-19 11:35:39 +00005645static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005646 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005647 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005648 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005649 zErr = dlerror();
5650 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005651 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005652 }
drh6c7d5c52008-11-21 20:32:33 +00005653 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005654}
drh1875f7a2008-12-08 18:19:17 +00005655static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5656 /*
5657 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5658 ** cast into a pointer to a function. And yet the library dlsym() routine
5659 ** returns a void* which is really a pointer to a function. So how do we
5660 ** use dlsym() with -pedantic-errors?
5661 **
5662 ** Variable x below is defined to be a pointer to a function taking
5663 ** parameters void* and const char* and returning a pointer to a function.
5664 ** We initialize x by assigning it a pointer to the dlsym() function.
5665 ** (That assignment requires a cast.) Then we call the function that
5666 ** x points to.
5667 **
5668 ** This work-around is unlikely to work correctly on any system where
5669 ** you really cannot cast a function pointer into void*. But then, on the
5670 ** other hand, dlsym() will not work on such a system either, so we have
5671 ** not really lost anything.
5672 */
5673 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005674 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005675 x = (void(*(*)(void*,const char*))(void))dlsym;
5676 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005677}
danielk1977397d65f2008-11-19 11:35:39 +00005678static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5679 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005680 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005681}
danielk1977b4b47412007-08-17 15:53:36 +00005682#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5683 #define unixDlOpen 0
5684 #define unixDlError 0
5685 #define unixDlSym 0
5686 #define unixDlClose 0
5687#endif
5688
5689/*
danielk197790949c22007-08-17 16:50:38 +00005690** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005691*/
danielk1977397d65f2008-11-19 11:35:39 +00005692static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5693 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005694 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005695
drhbbd42a62004-05-22 17:41:58 +00005696 /* We have to initialize zBuf to prevent valgrind from reporting
5697 ** errors. The reports issued by valgrind are incorrect - we would
5698 ** prefer that the randomness be increased by making use of the
5699 ** uninitialized space in zBuf - but valgrind errors tend to worry
5700 ** some users. Rather than argue, it seems easier just to initialize
5701 ** the whole array and silence valgrind, even if that means less randomness
5702 ** in the random seed.
5703 **
5704 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005705 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005706 ** tests repeatable.
5707 */
danielk1977b4b47412007-08-17 15:53:36 +00005708 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005709#if !defined(SQLITE_TEST)
5710 {
drhc18b4042012-02-10 03:10:27 +00005711 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005712 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005713 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005714 time_t t;
5715 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005716 memcpy(zBuf, &t, sizeof(t));
5717 pid = getpid();
5718 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005719 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005720 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005721 }else{
drhc18b4042012-02-10 03:10:27 +00005722 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005723 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005724 }
drhbbd42a62004-05-22 17:41:58 +00005725 }
5726#endif
drh72cbd072008-10-14 17:58:38 +00005727 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005728}
5729
danielk1977b4b47412007-08-17 15:53:36 +00005730
drhbbd42a62004-05-22 17:41:58 +00005731/*
5732** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005733** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005734** The return value is the number of microseconds of sleep actually
5735** requested from the underlying operating system, a number which
5736** might be greater than or equal to the argument, but not less
5737** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005738*/
danielk1977397d65f2008-11-19 11:35:39 +00005739static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005740#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005741 struct timespec sp;
5742
5743 sp.tv_sec = microseconds / 1000000;
5744 sp.tv_nsec = (microseconds % 1000000) * 1000;
5745 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005746 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005747 return microseconds;
5748#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005749 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005750 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005751 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005752#else
danielk1977b4b47412007-08-17 15:53:36 +00005753 int seconds = (microseconds+999999)/1000000;
5754 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005755 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005756 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005757#endif
drh88f474a2006-01-02 20:00:12 +00005758}
5759
5760/*
drh6b9d6dd2008-12-03 19:34:47 +00005761** The following variable, if set to a non-zero value, is interpreted as
5762** the number of seconds since 1970 and is used to set the result of
5763** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005764*/
5765#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005766int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005767#endif
5768
5769/*
drhb7e8ea22010-05-03 14:32:30 +00005770** Find the current time (in Universal Coordinated Time). Write into *piNow
5771** the current time and date as a Julian Day number times 86_400_000. In
5772** other words, write into *piNow the number of milliseconds since the Julian
5773** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5774** proleptic Gregorian calendar.
5775**
drh31702252011-10-12 23:13:43 +00005776** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5777** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005778*/
5779static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5780 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005781 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005782#if defined(NO_GETTOD)
5783 time_t t;
5784 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005785 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005786#elif OS_VXWORKS
5787 struct timespec sNow;
5788 clock_gettime(CLOCK_REALTIME, &sNow);
5789 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5790#else
5791 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005792 if( gettimeofday(&sNow, 0)==0 ){
5793 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5794 }else{
5795 rc = SQLITE_ERROR;
5796 }
drhb7e8ea22010-05-03 14:32:30 +00005797#endif
5798
5799#ifdef SQLITE_TEST
5800 if( sqlite3_current_time ){
5801 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5802 }
5803#endif
5804 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005805 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005806}
5807
5808/*
drhbbd42a62004-05-22 17:41:58 +00005809** Find the current time (in Universal Coordinated Time). Write the
5810** current time and date as a Julian Day number into *prNow and
5811** return 0. Return 1 if the time and date cannot be found.
5812*/
danielk1977397d65f2008-11-19 11:35:39 +00005813static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005814 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005815 int rc;
drhff828942010-06-26 21:34:06 +00005816 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005817 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005818 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005819 return rc;
drhbbd42a62004-05-22 17:41:58 +00005820}
danielk1977b4b47412007-08-17 15:53:36 +00005821
drh6b9d6dd2008-12-03 19:34:47 +00005822/*
5823** We added the xGetLastError() method with the intention of providing
5824** better low-level error messages when operating-system problems come up
5825** during SQLite operation. But so far, none of that has been implemented
5826** in the core. So this routine is never called. For now, it is merely
5827** a place-holder.
5828*/
danielk1977397d65f2008-11-19 11:35:39 +00005829static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5830 UNUSED_PARAMETER(NotUsed);
5831 UNUSED_PARAMETER(NotUsed2);
5832 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005833 return 0;
5834}
5835
drhf2424c52010-04-26 00:04:55 +00005836
5837/*
drh734c9862008-11-28 15:37:20 +00005838************************ End of sqlite3_vfs methods ***************************
5839******************************************************************************/
5840
drh715ff302008-12-03 22:32:44 +00005841/******************************************************************************
5842************************** Begin Proxy Locking ********************************
5843**
5844** Proxy locking is a "uber-locking-method" in this sense: It uses the
5845** other locking methods on secondary lock files. Proxy locking is a
5846** meta-layer over top of the primitive locking implemented above. For
5847** this reason, the division that implements of proxy locking is deferred
5848** until late in the file (here) after all of the other I/O methods have
5849** been defined - so that the primitive locking methods are available
5850** as services to help with the implementation of proxy locking.
5851**
5852****
5853**
5854** The default locking schemes in SQLite use byte-range locks on the
5855** database file to coordinate safe, concurrent access by multiple readers
5856** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5857** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5858** as POSIX read & write locks over fixed set of locations (via fsctl),
5859** on AFP and SMB only exclusive byte-range locks are available via fsctl
5860** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5861** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5862** address in the shared range is taken for a SHARED lock, the entire
5863** shared range is taken for an EXCLUSIVE lock):
5864**
drhf2f105d2012-08-20 15:53:54 +00005865** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00005866** RESERVED_BYTE 0x40000001
5867** SHARED_RANGE 0x40000002 -> 0x40000200
5868**
5869** This works well on the local file system, but shows a nearly 100x
5870** slowdown in read performance on AFP because the AFP client disables
5871** the read cache when byte-range locks are present. Enabling the read
5872** cache exposes a cache coherency problem that is present on all OS X
5873** supported network file systems. NFS and AFP both observe the
5874** close-to-open semantics for ensuring cache coherency
5875** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5876** address the requirements for concurrent database access by multiple
5877** readers and writers
5878** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5879**
5880** To address the performance and cache coherency issues, proxy file locking
5881** changes the way database access is controlled by limiting access to a
5882** single host at a time and moving file locks off of the database file
5883** and onto a proxy file on the local file system.
5884**
5885**
5886** Using proxy locks
5887** -----------------
5888**
5889** C APIs
5890**
5891** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5892** <proxy_path> | ":auto:");
5893** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5894**
5895**
5896** SQL pragmas
5897**
5898** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5899** PRAGMA [database.]lock_proxy_file
5900**
5901** Specifying ":auto:" means that if there is a conch file with a matching
5902** host ID in it, the proxy path in the conch file will be used, otherwise
5903** a proxy path based on the user's temp dir
5904** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5905** actual proxy file name is generated from the name and path of the
5906** database file. For example:
5907**
5908** For database path "/Users/me/foo.db"
5909** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5910**
5911** Once a lock proxy is configured for a database connection, it can not
5912** be removed, however it may be switched to a different proxy path via
5913** the above APIs (assuming the conch file is not being held by another
5914** connection or process).
5915**
5916**
5917** How proxy locking works
5918** -----------------------
5919**
5920** Proxy file locking relies primarily on two new supporting files:
5921**
5922** * conch file to limit access to the database file to a single host
5923** at a time
5924**
5925** * proxy file to act as a proxy for the advisory locks normally
5926** taken on the database
5927**
5928** The conch file - to use a proxy file, sqlite must first "hold the conch"
5929** by taking an sqlite-style shared lock on the conch file, reading the
5930** contents and comparing the host's unique host ID (see below) and lock
5931** proxy path against the values stored in the conch. The conch file is
5932** stored in the same directory as the database file and the file name
5933** is patterned after the database file name as ".<databasename>-conch".
5934** If the conch file does not exist, or it's contents do not match the
5935** host ID and/or proxy path, then the lock is escalated to an exclusive
5936** lock and the conch file contents is updated with the host ID and proxy
5937** path and the lock is downgraded to a shared lock again. If the conch
5938** is held by another process (with a shared lock), the exclusive lock
5939** will fail and SQLITE_BUSY is returned.
5940**
5941** The proxy file - a single-byte file used for all advisory file locks
5942** normally taken on the database file. This allows for safe sharing
5943** of the database file for multiple readers and writers on the same
5944** host (the conch ensures that they all use the same local lock file).
5945**
drh715ff302008-12-03 22:32:44 +00005946** Requesting the lock proxy does not immediately take the conch, it is
5947** only taken when the first request to lock database file is made.
5948** This matches the semantics of the traditional locking behavior, where
5949** opening a connection to a database file does not take a lock on it.
5950** The shared lock and an open file descriptor are maintained until
5951** the connection to the database is closed.
5952**
5953** The proxy file and the lock file are never deleted so they only need
5954** to be created the first time they are used.
5955**
5956** Configuration options
5957** ---------------------
5958**
5959** SQLITE_PREFER_PROXY_LOCKING
5960**
5961** Database files accessed on non-local file systems are
5962** automatically configured for proxy locking, lock files are
5963** named automatically using the same logic as
5964** PRAGMA lock_proxy_file=":auto:"
5965**
5966** SQLITE_PROXY_DEBUG
5967**
5968** Enables the logging of error messages during host id file
5969** retrieval and creation
5970**
drh715ff302008-12-03 22:32:44 +00005971** LOCKPROXYDIR
5972**
5973** Overrides the default directory used for lock proxy files that
5974** are named automatically via the ":auto:" setting
5975**
5976** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5977**
5978** Permissions to use when creating a directory for storing the
5979** lock proxy files, only used when LOCKPROXYDIR is not set.
5980**
5981**
5982** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5983** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5984** force proxy locking to be used for every database file opened, and 0
5985** will force automatic proxy locking to be disabled for all database
5986** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5987** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5988*/
5989
5990/*
5991** Proxy locking is only available on MacOSX
5992*/
drhd2cb50b2009-01-09 21:41:17 +00005993#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005994
drh715ff302008-12-03 22:32:44 +00005995/*
5996** The proxyLockingContext has the path and file structures for the remote
5997** and local proxy files in it
5998*/
5999typedef struct proxyLockingContext proxyLockingContext;
6000struct proxyLockingContext {
6001 unixFile *conchFile; /* Open conch file */
6002 char *conchFilePath; /* Name of the conch file */
6003 unixFile *lockProxy; /* Open proxy lock file */
6004 char *lockProxyPath; /* Name of the proxy lock file */
6005 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006006 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006007 void *oldLockingContext; /* Original lockingcontext to restore on close */
6008 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6009};
6010
drh7ed97b92010-01-20 13:07:21 +00006011/*
6012** The proxy lock file path for the database at dbPath is written into lPath,
6013** which must point to valid, writable memory large enough for a maxLen length
6014** file path.
drh715ff302008-12-03 22:32:44 +00006015*/
drh715ff302008-12-03 22:32:44 +00006016static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6017 int len;
6018 int dbLen;
6019 int i;
6020
6021#ifdef LOCKPROXYDIR
6022 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6023#else
6024# ifdef _CS_DARWIN_USER_TEMP_DIR
6025 {
drh7ed97b92010-01-20 13:07:21 +00006026 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006027 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6028 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006029 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006030 }
drh7ed97b92010-01-20 13:07:21 +00006031 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006032 }
6033# else
6034 len = strlcpy(lPath, "/tmp/", maxLen);
6035# endif
6036#endif
6037
6038 if( lPath[len-1]!='/' ){
6039 len = strlcat(lPath, "/", maxLen);
6040 }
6041
6042 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006043 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006044 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006045 char c = dbPath[i];
6046 lPath[i+len] = (c=='/')?'_':c;
6047 }
6048 lPath[i+len]='\0';
6049 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006050 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006051 return SQLITE_OK;
6052}
6053
drh7ed97b92010-01-20 13:07:21 +00006054/*
6055 ** Creates the lock file and any missing directories in lockPath
6056 */
6057static int proxyCreateLockPath(const char *lockPath){
6058 int i, len;
6059 char buf[MAXPATHLEN];
6060 int start = 0;
6061
6062 assert(lockPath!=NULL);
6063 /* try to create all the intermediate directories */
6064 len = (int)strlen(lockPath);
6065 buf[0] = lockPath[0];
6066 for( i=1; i<len; i++ ){
6067 if( lockPath[i] == '/' && (i - start > 0) ){
6068 /* only mkdir if leaf dir != "." or "/" or ".." */
6069 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6070 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6071 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006072 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006073 int err=errno;
6074 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006075 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006076 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006077 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006078 return err;
6079 }
6080 }
6081 }
6082 start=i+1;
6083 }
6084 buf[i] = lockPath[i];
6085 }
drh308c2a52010-05-14 11:30:18 +00006086 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006087 return 0;
6088}
6089
drh715ff302008-12-03 22:32:44 +00006090/*
6091** Create a new VFS file descriptor (stored in memory obtained from
6092** sqlite3_malloc) and open the file named "path" in the file descriptor.
6093**
6094** The caller is responsible not only for closing the file descriptor
6095** but also for freeing the memory associated with the file descriptor.
6096*/
drh7ed97b92010-01-20 13:07:21 +00006097static int proxyCreateUnixFile(
6098 const char *path, /* path for the new unixFile */
6099 unixFile **ppFile, /* unixFile created and returned by ref */
6100 int islockfile /* if non zero missing dirs will be created */
6101) {
6102 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006103 unixFile *pNew;
6104 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006105 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006106 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006107 int terrno = 0;
6108 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006109
drh7ed97b92010-01-20 13:07:21 +00006110 /* 1. first try to open/create the file
6111 ** 2. if that fails, and this is a lock file (not-conch), try creating
6112 ** the parent directories and then try again.
6113 ** 3. if that fails, try to open the file read-only
6114 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6115 */
6116 pUnused = findReusableFd(path, openFlags);
6117 if( pUnused ){
6118 fd = pUnused->fd;
6119 }else{
6120 pUnused = sqlite3_malloc(sizeof(*pUnused));
6121 if( !pUnused ){
6122 return SQLITE_NOMEM;
6123 }
6124 }
6125 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006126 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006127 terrno = errno;
6128 if( fd<0 && errno==ENOENT && islockfile ){
6129 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006130 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006131 }
6132 }
6133 }
6134 if( fd<0 ){
6135 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006136 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006137 terrno = errno;
6138 }
6139 if( fd<0 ){
6140 if( islockfile ){
6141 return SQLITE_BUSY;
6142 }
6143 switch (terrno) {
6144 case EACCES:
6145 return SQLITE_PERM;
6146 case EIO:
6147 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6148 default:
drh9978c972010-02-23 17:36:32 +00006149 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006150 }
6151 }
6152
6153 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6154 if( pNew==NULL ){
6155 rc = SQLITE_NOMEM;
6156 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006157 }
6158 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006159 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006160 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006161 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006162 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006163 pUnused->fd = fd;
6164 pUnused->flags = openFlags;
6165 pNew->pUnused = pUnused;
6166
drhc02a43a2012-01-10 23:18:38 +00006167 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006168 if( rc==SQLITE_OK ){
6169 *ppFile = pNew;
6170 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006171 }
drh7ed97b92010-01-20 13:07:21 +00006172end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006173 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006174 sqlite3_free(pNew);
6175 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006176 return rc;
6177}
6178
drh7ed97b92010-01-20 13:07:21 +00006179#ifdef SQLITE_TEST
6180/* simulate multiple hosts by creating unique hostid file paths */
6181int sqlite3_hostid_num = 0;
6182#endif
6183
6184#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6185
drh0ab216a2010-07-02 17:10:40 +00006186/* Not always defined in the headers as it ought to be */
6187extern int gethostuuid(uuid_t id, const struct timespec *wait);
6188
drh7ed97b92010-01-20 13:07:21 +00006189/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6190** bytes of writable memory.
6191*/
6192static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006193 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6194 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006195#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6196 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006197 {
6198 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6199 if( gethostuuid(pHostID, &timeout) ){
6200 int err = errno;
6201 if( pError ){
6202 *pError = err;
6203 }
6204 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006205 }
drh7ed97b92010-01-20 13:07:21 +00006206 }
drh3d4435b2011-08-26 20:55:50 +00006207#else
6208 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006209#endif
drh7ed97b92010-01-20 13:07:21 +00006210#ifdef SQLITE_TEST
6211 /* simulate multiple hosts by creating unique hostid file paths */
6212 if( sqlite3_hostid_num != 0){
6213 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6214 }
6215#endif
6216
6217 return SQLITE_OK;
6218}
6219
6220/* The conch file contains the header, host id and lock file path
6221 */
6222#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6223#define PROXY_HEADERLEN 1 /* conch file header length */
6224#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6225#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6226
6227/*
6228** Takes an open conch file, copies the contents to a new path and then moves
6229** it back. The newly created file's file descriptor is assigned to the
6230** conch file structure and finally the original conch file descriptor is
6231** closed. Returns zero if successful.
6232*/
6233static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6234 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6235 unixFile *conchFile = pCtx->conchFile;
6236 char tPath[MAXPATHLEN];
6237 char buf[PROXY_MAXCONCHLEN];
6238 char *cPath = pCtx->conchFilePath;
6239 size_t readLen = 0;
6240 size_t pathLen = 0;
6241 char errmsg[64] = "";
6242 int fd = -1;
6243 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006244 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006245
6246 /* create a new path by replace the trailing '-conch' with '-break' */
6247 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6248 if( pathLen>MAXPATHLEN || pathLen<6 ||
6249 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006250 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006251 goto end_breaklock;
6252 }
6253 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006254 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006255 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006256 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006257 goto end_breaklock;
6258 }
6259 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006260 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006261 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006262 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006263 goto end_breaklock;
6264 }
drhe562be52011-03-02 18:01:10 +00006265 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006266 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006267 goto end_breaklock;
6268 }
6269 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006270 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006271 goto end_breaklock;
6272 }
6273 rc = 0;
6274 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006275 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006276 conchFile->h = fd;
6277 conchFile->openFlags = O_RDWR | O_CREAT;
6278
6279end_breaklock:
6280 if( rc ){
6281 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006282 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006283 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006284 }
6285 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6286 }
6287 return rc;
6288}
6289
6290/* Take the requested lock on the conch file and break a stale lock if the
6291** host id matches.
6292*/
6293static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6294 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6295 unixFile *conchFile = pCtx->conchFile;
6296 int rc = SQLITE_OK;
6297 int nTries = 0;
6298 struct timespec conchModTime;
6299
drh3d4435b2011-08-26 20:55:50 +00006300 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006301 do {
6302 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6303 nTries ++;
6304 if( rc==SQLITE_BUSY ){
6305 /* If the lock failed (busy):
6306 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6307 * 2nd try: fail if the mod time changed or host id is different, wait
6308 * 10 sec and try again
6309 * 3rd try: break the lock unless the mod time has changed.
6310 */
6311 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006312 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006313 pFile->lastErrno = errno;
6314 return SQLITE_IOERR_LOCK;
6315 }
6316
6317 if( nTries==1 ){
6318 conchModTime = buf.st_mtimespec;
6319 usleep(500000); /* wait 0.5 sec and try the lock again*/
6320 continue;
6321 }
6322
6323 assert( nTries>1 );
6324 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6325 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6326 return SQLITE_BUSY;
6327 }
6328
6329 if( nTries==2 ){
6330 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006331 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006332 if( len<0 ){
6333 pFile->lastErrno = errno;
6334 return SQLITE_IOERR_LOCK;
6335 }
6336 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6337 /* don't break the lock if the host id doesn't match */
6338 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6339 return SQLITE_BUSY;
6340 }
6341 }else{
6342 /* don't break the lock on short read or a version mismatch */
6343 return SQLITE_BUSY;
6344 }
6345 usleep(10000000); /* wait 10 sec and try the lock again */
6346 continue;
6347 }
6348
6349 assert( nTries==3 );
6350 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6351 rc = SQLITE_OK;
6352 if( lockType==EXCLUSIVE_LOCK ){
6353 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6354 }
6355 if( !rc ){
6356 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6357 }
6358 }
6359 }
6360 } while( rc==SQLITE_BUSY && nTries<3 );
6361
6362 return rc;
6363}
6364
6365/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006366** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6367** lockPath means that the lockPath in the conch file will be used if the
6368** host IDs match, or a new lock path will be generated automatically
6369** and written to the conch file.
6370*/
6371static int proxyTakeConch(unixFile *pFile){
6372 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6373
drh7ed97b92010-01-20 13:07:21 +00006374 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006375 return SQLITE_OK;
6376 }else{
6377 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006378 uuid_t myHostID;
6379 int pError = 0;
6380 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006381 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006382 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006383 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006384 int createConch = 0;
6385 int hostIdMatch = 0;
6386 int readLen = 0;
6387 int tryOldLockPath = 0;
6388 int forceNewLockPath = 0;
6389
drh308c2a52010-05-14 11:30:18 +00006390 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6391 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006392
drh7ed97b92010-01-20 13:07:21 +00006393 rc = proxyGetHostID(myHostID, &pError);
6394 if( (rc&0xff)==SQLITE_IOERR ){
6395 pFile->lastErrno = pError;
6396 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006397 }
drh7ed97b92010-01-20 13:07:21 +00006398 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006399 if( rc!=SQLITE_OK ){
6400 goto end_takeconch;
6401 }
drh7ed97b92010-01-20 13:07:21 +00006402 /* read the existing conch file */
6403 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6404 if( readLen<0 ){
6405 /* I/O error: lastErrno set by seekAndRead */
6406 pFile->lastErrno = conchFile->lastErrno;
6407 rc = SQLITE_IOERR_READ;
6408 goto end_takeconch;
6409 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6410 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6411 /* a short read or version format mismatch means we need to create a new
6412 ** conch file.
6413 */
6414 createConch = 1;
6415 }
6416 /* if the host id matches and the lock path already exists in the conch
6417 ** we'll try to use the path there, if we can't open that path, we'll
6418 ** retry with a new auto-generated path
6419 */
6420 do { /* in case we need to try again for an :auto: named lock file */
6421
6422 if( !createConch && !forceNewLockPath ){
6423 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6424 PROXY_HOSTIDLEN);
6425 /* if the conch has data compare the contents */
6426 if( !pCtx->lockProxyPath ){
6427 /* for auto-named local lock file, just check the host ID and we'll
6428 ** use the local lock file path that's already in there
6429 */
6430 if( hostIdMatch ){
6431 size_t pathLen = (readLen - PROXY_PATHINDEX);
6432
6433 if( pathLen>=MAXPATHLEN ){
6434 pathLen=MAXPATHLEN-1;
6435 }
6436 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6437 lockPath[pathLen] = 0;
6438 tempLockPath = lockPath;
6439 tryOldLockPath = 1;
6440 /* create a copy of the lock path if the conch is taken */
6441 goto end_takeconch;
6442 }
6443 }else if( hostIdMatch
6444 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6445 readLen-PROXY_PATHINDEX)
6446 ){
6447 /* conch host and lock path match */
6448 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006449 }
drh7ed97b92010-01-20 13:07:21 +00006450 }
6451
6452 /* if the conch isn't writable and doesn't match, we can't take it */
6453 if( (conchFile->openFlags&O_RDWR) == 0 ){
6454 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006455 goto end_takeconch;
6456 }
drh7ed97b92010-01-20 13:07:21 +00006457
6458 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006459 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006460 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6461 tempLockPath = lockPath;
6462 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006463 }
drh7ed97b92010-01-20 13:07:21 +00006464
6465 /* update conch with host and path (this will fail if other process
6466 ** has a shared lock already), if the host id matches, use the big
6467 ** stick.
drh715ff302008-12-03 22:32:44 +00006468 */
drh7ed97b92010-01-20 13:07:21 +00006469 futimes(conchFile->h, NULL);
6470 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006471 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006472 /* We are trying for an exclusive lock but another thread in this
6473 ** same process is still holding a shared lock. */
6474 rc = SQLITE_BUSY;
6475 } else {
6476 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006477 }
drh715ff302008-12-03 22:32:44 +00006478 }else{
drh7ed97b92010-01-20 13:07:21 +00006479 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006480 }
drh7ed97b92010-01-20 13:07:21 +00006481 if( rc==SQLITE_OK ){
6482 char writeBuffer[PROXY_MAXCONCHLEN];
6483 int writeSize = 0;
6484
6485 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6486 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6487 if( pCtx->lockProxyPath!=NULL ){
6488 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6489 }else{
6490 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6491 }
6492 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006493 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006494 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6495 fsync(conchFile->h);
6496 /* If we created a new conch file (not just updated the contents of a
6497 ** valid conch file), try to match the permissions of the database
6498 */
6499 if( rc==SQLITE_OK && createConch ){
6500 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006501 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006502 if( err==0 ){
6503 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6504 S_IROTH|S_IWOTH);
6505 /* try to match the database file R/W permissions, ignore failure */
6506#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006507 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006508#else
drhff812312011-02-23 13:33:46 +00006509 do{
drhe562be52011-03-02 18:01:10 +00006510 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006511 }while( rc==(-1) && errno==EINTR );
6512 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006513 int code = errno;
6514 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6515 cmode, code, strerror(code));
6516 } else {
6517 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6518 }
6519 }else{
6520 int code = errno;
6521 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6522 err, code, strerror(code));
6523#endif
6524 }
drh715ff302008-12-03 22:32:44 +00006525 }
6526 }
drh7ed97b92010-01-20 13:07:21 +00006527 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6528
6529 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006530 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006531 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006532 int fd;
drh7ed97b92010-01-20 13:07:21 +00006533 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006534 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006535 }
6536 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006537 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006538 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006539 if( fd>=0 ){
6540 pFile->h = fd;
6541 }else{
drh9978c972010-02-23 17:36:32 +00006542 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006543 during locking */
6544 }
6545 }
6546 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6547 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6548 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6549 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6550 /* we couldn't create the proxy lock file with the old lock file path
6551 ** so try again via auto-naming
6552 */
6553 forceNewLockPath = 1;
6554 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006555 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006556 }
6557 }
6558 if( rc==SQLITE_OK ){
6559 /* Need to make a copy of path if we extracted the value
6560 ** from the conch file or the path was allocated on the stack
6561 */
6562 if( tempLockPath ){
6563 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6564 if( !pCtx->lockProxyPath ){
6565 rc = SQLITE_NOMEM;
6566 }
6567 }
6568 }
6569 if( rc==SQLITE_OK ){
6570 pCtx->conchHeld = 1;
6571
6572 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6573 afpLockingContext *afpCtx;
6574 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6575 afpCtx->dbPath = pCtx->lockProxyPath;
6576 }
6577 } else {
6578 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6579 }
drh308c2a52010-05-14 11:30:18 +00006580 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6581 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006582 return rc;
drh308c2a52010-05-14 11:30:18 +00006583 } while (1); /* in case we need to retry the :auto: lock file -
6584 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006585 }
6586}
6587
6588/*
6589** If pFile holds a lock on a conch file, then release that lock.
6590*/
6591static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006592 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006593 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6594 unixFile *conchFile; /* Name of the conch file */
6595
6596 pCtx = (proxyLockingContext *)pFile->lockingContext;
6597 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006598 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006599 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006600 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006601 if( pCtx->conchHeld>0 ){
6602 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6603 }
drh715ff302008-12-03 22:32:44 +00006604 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006605 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6606 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006607 return rc;
6608}
6609
6610/*
6611** Given the name of a database file, compute the name of its conch file.
6612** Store the conch filename in memory obtained from sqlite3_malloc().
6613** Make *pConchPath point to the new name. Return SQLITE_OK on success
6614** or SQLITE_NOMEM if unable to obtain memory.
6615**
6616** The caller is responsible for ensuring that the allocated memory
6617** space is eventually freed.
6618**
6619** *pConchPath is set to NULL if a memory allocation error occurs.
6620*/
6621static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6622 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006623 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006624 char *conchPath; /* buffer in which to construct conch name */
6625
6626 /* Allocate space for the conch filename and initialize the name to
6627 ** the name of the original database file. */
6628 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6629 if( conchPath==0 ){
6630 return SQLITE_NOMEM;
6631 }
6632 memcpy(conchPath, dbPath, len+1);
6633
6634 /* now insert a "." before the last / character */
6635 for( i=(len-1); i>=0; i-- ){
6636 if( conchPath[i]=='/' ){
6637 i++;
6638 break;
6639 }
6640 }
6641 conchPath[i]='.';
6642 while ( i<len ){
6643 conchPath[i+1]=dbPath[i];
6644 i++;
6645 }
6646
6647 /* append the "-conch" suffix to the file */
6648 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006649 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006650
6651 return SQLITE_OK;
6652}
6653
6654
6655/* Takes a fully configured proxy locking-style unix file and switches
6656** the local lock file path
6657*/
6658static int switchLockProxyPath(unixFile *pFile, const char *path) {
6659 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6660 char *oldPath = pCtx->lockProxyPath;
6661 int rc = SQLITE_OK;
6662
drh308c2a52010-05-14 11:30:18 +00006663 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006664 return SQLITE_BUSY;
6665 }
6666
6667 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6668 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6669 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6670 return SQLITE_OK;
6671 }else{
6672 unixFile *lockProxy = pCtx->lockProxy;
6673 pCtx->lockProxy=NULL;
6674 pCtx->conchHeld = 0;
6675 if( lockProxy!=NULL ){
6676 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6677 if( rc ) return rc;
6678 sqlite3_free(lockProxy);
6679 }
6680 sqlite3_free(oldPath);
6681 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6682 }
6683
6684 return rc;
6685}
6686
6687/*
6688** pFile is a file that has been opened by a prior xOpen call. dbPath
6689** is a string buffer at least MAXPATHLEN+1 characters in size.
6690**
6691** This routine find the filename associated with pFile and writes it
6692** int dbPath.
6693*/
6694static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006695#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006696 if( pFile->pMethod == &afpIoMethods ){
6697 /* afp style keeps a reference to the db path in the filePath field
6698 ** of the struct */
drhea678832008-12-10 19:26:22 +00006699 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006700 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6701 } else
drh715ff302008-12-03 22:32:44 +00006702#endif
6703 if( pFile->pMethod == &dotlockIoMethods ){
6704 /* dot lock style uses the locking context to store the dot lock
6705 ** file path */
6706 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6707 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6708 }else{
6709 /* all other styles use the locking context to store the db file path */
6710 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006711 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006712 }
6713 return SQLITE_OK;
6714}
6715
6716/*
6717** Takes an already filled in unix file and alters it so all file locking
6718** will be performed on the local proxy lock file. The following fields
6719** are preserved in the locking context so that they can be restored and
6720** the unix structure properly cleaned up at close time:
6721** ->lockingContext
6722** ->pMethod
6723*/
6724static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6725 proxyLockingContext *pCtx;
6726 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6727 char *lockPath=NULL;
6728 int rc = SQLITE_OK;
6729
drh308c2a52010-05-14 11:30:18 +00006730 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006731 return SQLITE_BUSY;
6732 }
6733 proxyGetDbPathForUnixFile(pFile, dbPath);
6734 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6735 lockPath=NULL;
6736 }else{
6737 lockPath=(char *)path;
6738 }
6739
drh308c2a52010-05-14 11:30:18 +00006740 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6741 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006742
6743 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6744 if( pCtx==0 ){
6745 return SQLITE_NOMEM;
6746 }
6747 memset(pCtx, 0, sizeof(*pCtx));
6748
6749 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6750 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006751 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6752 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6753 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6754 ** (c) the file system is read-only, then enable no-locking access.
6755 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6756 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6757 */
6758 struct statfs fsInfo;
6759 struct stat conchInfo;
6760 int goLockless = 0;
6761
drh99ab3b12011-03-02 15:09:07 +00006762 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006763 int err = errno;
6764 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6765 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6766 }
6767 }
6768 if( goLockless ){
6769 pCtx->conchHeld = -1; /* read only FS/ lockless */
6770 rc = SQLITE_OK;
6771 }
6772 }
drh715ff302008-12-03 22:32:44 +00006773 }
6774 if( rc==SQLITE_OK && lockPath ){
6775 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6776 }
6777
6778 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006779 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6780 if( pCtx->dbPath==NULL ){
6781 rc = SQLITE_NOMEM;
6782 }
6783 }
6784 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006785 /* all memory is allocated, proxys are created and assigned,
6786 ** switch the locking context and pMethod then return.
6787 */
drh715ff302008-12-03 22:32:44 +00006788 pCtx->oldLockingContext = pFile->lockingContext;
6789 pFile->lockingContext = pCtx;
6790 pCtx->pOldMethod = pFile->pMethod;
6791 pFile->pMethod = &proxyIoMethods;
6792 }else{
6793 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006794 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006795 sqlite3_free(pCtx->conchFile);
6796 }
drhd56b1212010-08-11 06:14:15 +00006797 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006798 sqlite3_free(pCtx->conchFilePath);
6799 sqlite3_free(pCtx);
6800 }
drh308c2a52010-05-14 11:30:18 +00006801 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6802 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006803 return rc;
6804}
6805
6806
6807/*
6808** This routine handles sqlite3_file_control() calls that are specific
6809** to proxy locking.
6810*/
6811static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6812 switch( op ){
6813 case SQLITE_GET_LOCKPROXYFILE: {
6814 unixFile *pFile = (unixFile*)id;
6815 if( pFile->pMethod == &proxyIoMethods ){
6816 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6817 proxyTakeConch(pFile);
6818 if( pCtx->lockProxyPath ){
6819 *(const char **)pArg = pCtx->lockProxyPath;
6820 }else{
6821 *(const char **)pArg = ":auto: (not held)";
6822 }
6823 } else {
6824 *(const char **)pArg = NULL;
6825 }
6826 return SQLITE_OK;
6827 }
6828 case SQLITE_SET_LOCKPROXYFILE: {
6829 unixFile *pFile = (unixFile*)id;
6830 int rc = SQLITE_OK;
6831 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6832 if( pArg==NULL || (const char *)pArg==0 ){
6833 if( isProxyStyle ){
6834 /* turn off proxy locking - not supported */
6835 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6836 }else{
6837 /* turn off proxy locking - already off - NOOP */
6838 rc = SQLITE_OK;
6839 }
6840 }else{
6841 const char *proxyPath = (const char *)pArg;
6842 if( isProxyStyle ){
6843 proxyLockingContext *pCtx =
6844 (proxyLockingContext*)pFile->lockingContext;
6845 if( !strcmp(pArg, ":auto:")
6846 || (pCtx->lockProxyPath &&
6847 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6848 ){
6849 rc = SQLITE_OK;
6850 }else{
6851 rc = switchLockProxyPath(pFile, proxyPath);
6852 }
6853 }else{
6854 /* turn on proxy file locking */
6855 rc = proxyTransformUnixFile(pFile, proxyPath);
6856 }
6857 }
6858 return rc;
6859 }
6860 default: {
6861 assert( 0 ); /* The call assures that only valid opcodes are sent */
6862 }
6863 }
6864 /*NOTREACHED*/
6865 return SQLITE_ERROR;
6866}
6867
6868/*
6869** Within this division (the proxying locking implementation) the procedures
6870** above this point are all utilities. The lock-related methods of the
6871** proxy-locking sqlite3_io_method object follow.
6872*/
6873
6874
6875/*
6876** This routine checks if there is a RESERVED lock held on the specified
6877** file by this or any other process. If such a lock is held, set *pResOut
6878** to a non-zero value otherwise *pResOut is set to zero. The return value
6879** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6880*/
6881static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6882 unixFile *pFile = (unixFile*)id;
6883 int rc = proxyTakeConch(pFile);
6884 if( rc==SQLITE_OK ){
6885 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006886 if( pCtx->conchHeld>0 ){
6887 unixFile *proxy = pCtx->lockProxy;
6888 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6889 }else{ /* conchHeld < 0 is lockless */
6890 pResOut=0;
6891 }
drh715ff302008-12-03 22:32:44 +00006892 }
6893 return rc;
6894}
6895
6896/*
drh308c2a52010-05-14 11:30:18 +00006897** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006898** of the following:
6899**
6900** (1) SHARED_LOCK
6901** (2) RESERVED_LOCK
6902** (3) PENDING_LOCK
6903** (4) EXCLUSIVE_LOCK
6904**
6905** Sometimes when requesting one lock state, additional lock states
6906** are inserted in between. The locking might fail on one of the later
6907** transitions leaving the lock state different from what it started but
6908** still short of its goal. The following chart shows the allowed
6909** transitions and the inserted intermediate states:
6910**
6911** UNLOCKED -> SHARED
6912** SHARED -> RESERVED
6913** SHARED -> (PENDING) -> EXCLUSIVE
6914** RESERVED -> (PENDING) -> EXCLUSIVE
6915** PENDING -> EXCLUSIVE
6916**
6917** This routine will only increase a lock. Use the sqlite3OsUnlock()
6918** routine to lower a locking level.
6919*/
drh308c2a52010-05-14 11:30:18 +00006920static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006921 unixFile *pFile = (unixFile*)id;
6922 int rc = proxyTakeConch(pFile);
6923 if( rc==SQLITE_OK ){
6924 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006925 if( pCtx->conchHeld>0 ){
6926 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006927 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6928 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006929 }else{
6930 /* conchHeld < 0 is lockless */
6931 }
drh715ff302008-12-03 22:32:44 +00006932 }
6933 return rc;
6934}
6935
6936
6937/*
drh308c2a52010-05-14 11:30:18 +00006938** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006939** must be either NO_LOCK or SHARED_LOCK.
6940**
6941** If the locking level of the file descriptor is already at or below
6942** the requested locking level, this routine is a no-op.
6943*/
drh308c2a52010-05-14 11:30:18 +00006944static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006945 unixFile *pFile = (unixFile*)id;
6946 int rc = proxyTakeConch(pFile);
6947 if( rc==SQLITE_OK ){
6948 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006949 if( pCtx->conchHeld>0 ){
6950 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006951 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6952 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006953 }else{
6954 /* conchHeld < 0 is lockless */
6955 }
drh715ff302008-12-03 22:32:44 +00006956 }
6957 return rc;
6958}
6959
6960/*
6961** Close a file that uses proxy locks.
6962*/
6963static int proxyClose(sqlite3_file *id) {
6964 if( id ){
6965 unixFile *pFile = (unixFile*)id;
6966 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6967 unixFile *lockProxy = pCtx->lockProxy;
6968 unixFile *conchFile = pCtx->conchFile;
6969 int rc = SQLITE_OK;
6970
6971 if( lockProxy ){
6972 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6973 if( rc ) return rc;
6974 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6975 if( rc ) return rc;
6976 sqlite3_free(lockProxy);
6977 pCtx->lockProxy = 0;
6978 }
6979 if( conchFile ){
6980 if( pCtx->conchHeld ){
6981 rc = proxyReleaseConch(pFile);
6982 if( rc ) return rc;
6983 }
6984 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6985 if( rc ) return rc;
6986 sqlite3_free(conchFile);
6987 }
drhd56b1212010-08-11 06:14:15 +00006988 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006989 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006990 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006991 /* restore the original locking context and pMethod then close it */
6992 pFile->lockingContext = pCtx->oldLockingContext;
6993 pFile->pMethod = pCtx->pOldMethod;
6994 sqlite3_free(pCtx);
6995 return pFile->pMethod->xClose(id);
6996 }
6997 return SQLITE_OK;
6998}
6999
7000
7001
drhd2cb50b2009-01-09 21:41:17 +00007002#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007003/*
7004** The proxy locking style is intended for use with AFP filesystems.
7005** And since AFP is only supported on MacOSX, the proxy locking is also
7006** restricted to MacOSX.
7007**
7008**
7009******************* End of the proxy lock implementation **********************
7010******************************************************************************/
7011
drh734c9862008-11-28 15:37:20 +00007012/*
danielk1977e339d652008-06-28 11:23:00 +00007013** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007014**
7015** This routine registers all VFS implementations for unix-like operating
7016** systems. This routine, and the sqlite3_os_end() routine that follows,
7017** should be the only routines in this file that are visible from other
7018** files.
drh6b9d6dd2008-12-03 19:34:47 +00007019**
7020** This routine is called once during SQLite initialization and by a
7021** single thread. The memory allocation and mutex subsystems have not
7022** necessarily been initialized when this routine is called, and so they
7023** should not be used.
drh153c62c2007-08-24 03:51:33 +00007024*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007025int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007026 /*
7027 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007028 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7029 ** to the "finder" function. (pAppData is a pointer to a pointer because
7030 ** silly C90 rules prohibit a void* from being cast to a function pointer
7031 ** and so we have to go through the intermediate pointer to avoid problems
7032 ** when compiling with -pedantic-errors on GCC.)
7033 **
7034 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007035 ** finder-function. The finder-function returns a pointer to the
7036 ** sqlite_io_methods object that implements the desired locking
7037 ** behaviors. See the division above that contains the IOMETHODS
7038 ** macro for addition information on finder-functions.
7039 **
7040 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7041 ** object. But the "autolockIoFinder" available on MacOSX does a little
7042 ** more than that; it looks at the filesystem type that hosts the
7043 ** database file and tries to choose an locking method appropriate for
7044 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007045 */
drh7708e972008-11-29 00:56:52 +00007046 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007047 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007048 sizeof(unixFile), /* szOsFile */ \
7049 MAX_PATHNAME, /* mxPathname */ \
7050 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007051 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007052 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007053 unixOpen, /* xOpen */ \
7054 unixDelete, /* xDelete */ \
7055 unixAccess, /* xAccess */ \
7056 unixFullPathname, /* xFullPathname */ \
7057 unixDlOpen, /* xDlOpen */ \
7058 unixDlError, /* xDlError */ \
7059 unixDlSym, /* xDlSym */ \
7060 unixDlClose, /* xDlClose */ \
7061 unixRandomness, /* xRandomness */ \
7062 unixSleep, /* xSleep */ \
7063 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007064 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007065 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007066 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007067 unixGetSystemCall, /* xGetSystemCall */ \
7068 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007069 }
7070
drh6b9d6dd2008-12-03 19:34:47 +00007071 /*
7072 ** All default VFSes for unix are contained in the following array.
7073 **
7074 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7075 ** by the SQLite core when the VFS is registered. So the following
7076 ** array cannot be const.
7077 */
danielk1977e339d652008-06-28 11:23:00 +00007078 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007079#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007080 UNIXVFS("unix", autolockIoFinder ),
7081#else
7082 UNIXVFS("unix", posixIoFinder ),
7083#endif
7084 UNIXVFS("unix-none", nolockIoFinder ),
7085 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007086 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007087#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007088 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007089#endif
7090#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007091 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007092#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007093 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007094#endif
chw78a13182009-04-07 05:35:03 +00007095#endif
drhd2cb50b2009-01-09 21:41:17 +00007096#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007097 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007098 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007099 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007100#endif
drh153c62c2007-08-24 03:51:33 +00007101 };
drh6b9d6dd2008-12-03 19:34:47 +00007102 unsigned int i; /* Loop counter */
7103
drh2aa5a002011-04-13 13:42:25 +00007104 /* Double-check that the aSyscall[] array has been constructed
7105 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhe1186ab2013-01-04 20:45:13 +00007106 assert( ArraySize(aSyscall)==21 );
drh2aa5a002011-04-13 13:42:25 +00007107
drh6b9d6dd2008-12-03 19:34:47 +00007108 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007109 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007110 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007111 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007112 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007113}
danielk1977e339d652008-06-28 11:23:00 +00007114
7115/*
drh6b9d6dd2008-12-03 19:34:47 +00007116** Shutdown the operating system interface.
7117**
7118** Some operating systems might need to do some cleanup in this routine,
7119** to release dynamically allocated objects. But not on unix.
7120** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007121*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007122int sqlite3_os_end(void){
7123 return SQLITE_OK;
7124}
drhdce8bdb2007-08-16 13:01:44 +00007125
danielk197729bafea2008-06-26 10:41:19 +00007126#endif /* SQLITE_OS_UNIX */